为什么不用静态方法?
来源:1-3 实战:封装数据库连接池
weixin_慕勒8187086
2020-05-28 04:30:50
UserDao 中的longin 和search_user_role这两个方法 为什么不直接用静态方法?
完全不需要实例化啊?
还是说这里使用静态方法有什么不好的地方?
2回答
好帮手慕笑蓉
2020-05-28
同学,你好。一般当方法中既不需要使用实例对象(如实例对象,实例属性),也不需要使用类对象(如类属性、类方法、创建实例等)时,是可以定义静态方法的。
如果解决了你的疑惑,请采纳,祝学习愉快~
weixin_慕勒8187086
提问者
2020-05-28
from db.mysql_db_pool import MysqlDbPool class UserDao(object): """ deal with t_user table """ __conn = None __cursor = None @staticmethod def login(username, password): """ find wether the user exist in the database :param username: username :param password: password :return: True if the user and password are all corrected, False, if one of them is not correct """ try: __conn = MysqlDbPool.get_pool().get_connection() __cursor = __conn.cursor() sql = ( "SELECT COUNT(*) FROM t_user WHERE username = %s AND AES_DECRYPT(UNHEX(password), 'HelloWorld') = %s") __cursor.execute(sql, (username, password)) result = __cursor.fetchone()[0] return True if result == 1 else False except Exception as e: print(e) finally: MysqlDbPool.release(__conn, __cursor) @staticmethod def search_user_role(username): """ get the urser's role :param username: the user's username :return: the user's role if not found, return None """ try: __conn = MysqlDbPool.get_pool().get_connection() __cursor = __conn.cursor() sql = ("SELECT r.role FROM t_user u JOIN t_role r ON u.role_id = r.id WHERE u.username = %s") __cursor.execute(sql, (username,)) result = __cursor.fetchone() if result is not None: result = result[0] return result except Exception as e: print(e) finally: MysqlDbPool.release(__conn, __cursor)
相似问题
回答 7