我有一個類正在接受一個Id並試圖更新變量current_account,但是當我打印出它沒有更新的current_account的細節。Python類變量不更新
任何人都有這個想法嗎?新的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__()
方法中設定的值。
請注意'None == account_id'很難用慣用的Python。 'None'是一個單例對象,使用'如果account_id是None:'來測試它。 – 2013-05-09 14:16:51
爲了記錄,你的問題是關於一個**實例變量**而不是一個類變量,當定義你自己的類時,你應該總是從'object'繼承,像這樣:'class UserData(object):' – 2013-05-09 14:18:19
Thanks有關信息,將按照建議更新班級。 – Nalum 2013-05-09 14:25:05