[英]Python class variable not updating
我有一個正在接收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__()
方法設置的值。
有很多裁員是非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']
因此模糊了您應該真正考慮更多不同的,信息豐富的名稱的意圖。
弄清楚它是什么。
數據正在改變,否則代碼庫中的位置。 它現在按預期工作。
謝謝大家指出我做錯的Python中心事情,很高興得到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.