2013-05-09 77 views
1

我有一個類正在接受一個I​​d並試圖更新變量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__()方法中設定的值。

+3

請注意'None == account_id'很難用慣用的Python。 'None'是一個單例對象,使用'如果account_id是None:'來測試它。 – 2013-05-09 14:16:51

+3

爲了記錄,你的問題是關於一個**實例變量**而不是一個類變量,當定義你自己的類時,你應該總是從'object'繼承,像這樣:'class UserData(object):' – 2013-05-09 14:18:19

+0

Thanks有關信息,將按照建議更新班級。 – Nalum 2013-05-09 14:25:05

回答

0

找出它是什麼。

數據在代碼庫中的其他位置正在更改。它現在按預期工作。

感謝大家指出我做錯了的Python中心事物,很高興認識它。

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_idcurrent_account['_id']因此模糊了你應該真正考慮更加明確的信息性名稱的意圖。

+0

感謝您的反饋,我已更新我的代碼以反映信息。我來自一個PHP背景,所以我想我會將一些代碼帶入我的代碼中。我想要做的是創建一個帳戶切換器。因此'my_account'是登錄的用戶帳戶,'current_account'是系統讀取的內容,所以用戶可以切換帳戶。也許有更好的方法來做到這一點。 'account_id'實際上是我們想要切換到的帳戶的ID。 – Nalum 2013-05-09 14:47:21