我有一个正在接收Id并尝试更新变量current_account的类,但是当我打印出current_account的详细信息时,它还没有更新。
有人有任何想法吗? python新手所以可能会做一些我看不到的蠢事。
class UserData:
def __init__(self, db_conn=None):
if None == db_conn:
raise Exception("DB Connection Required.")
self.db = db_conn
self.set_my_account()
self.set_accounts()
self.set_current_account()
def set_current_account(self, account_id=None):
print account_id
if None == account_id:
self.current_account = self.my_account
else:
if len(self.accounts) > 0:
for account in self.accounts:
if account['_id'] == account_id:
self.current_account = account
print self.current_account['_id']
else:
raise Exception("No accounts available.")
假设set_my_account()
获取帐户数据字典,set_accounts()
获取帐户数据字典列表。
所以,当我执行以下操作时:
user_data = UserData(db_conn=db_conn)
user_data.set_current_account(account_id=account_id)
其中db_conn
是有效的数据库连接,account_id
是有效的帐户ID。
我从以上两行中得到以下内容。
None
518a310356c02c0756764b4e
512754cfc1f3d16c25c350b7
因此None
值来自类的声明,然后接下来的两个来自对set_current_account()
的调用。第一个id
值是我要设置的值。第二个id
值是已经从类__init__()
方法设置的值。
答案 0 :(得分:2)
有很多裁员是非Pythonic的结构。我清理了代码以帮助我理解你想要做什么。
class UserData(object):
def __init__(self, db_conn):
self.db = db_conn
self.set_my_account()
self.set_accounts()
self.set_current_account()
def set_current_account(self, account_id=None):
print account_id
if account_id is None:
self.current_account = self.my_account
else:
if not self.accounts:
raise Exception("No accounts available.")
for account in self.accounts:
if account['_id'] == account_id:
self.current_account = account
print self.current_account['_id']
user_data = UserData(db_conn)
user_data.set_current_account(account_id)
当没有显式参数的调用无效时,您使用了默认参数(db_conn=None)
。是的,您现在可以拨打__init__(None)
,但也可以拨打__init__('Nalum')
;你无法防范一切。
通过移动“无帐户”例外,该块快速失败并保存一个级别的缩进。
调用UserData(db_conn = db_conn)有效但不必重复。
不幸的是,我仍然无法弄清楚你想要完成什么,这可能是最大的缺陷。变量名非常重要,可以帮助读者(可能是您的未来)理解代码。 current_account
,my_account
,account_id
和current_account['_id']
因此模糊了您应该真正考虑更明确,信息丰富的名称的意图。
答案 1 :(得分:0)
弄清楚它是什么。
数据正在改变代码库中的其他位置。它现在按预期工作。
感谢大家指出我做错的Python中心事情,很高兴得到它。