2015-04-16 26 views
0

在閱讀了幾篇文章之後,我仍然對正確實現一個帶有函數值的動態屬性的方法感到困惑。Python動態屬性值綁定到方法

從我接觸python開始就有一段時間了,現在我有點卡住了。

我有下面的類:

class RunkeeperUser(object): 

    def __init__(self, master): 
     self.master = master 
     # Get the user methods and set the attributes 
     for user_method, call in self.master.query('user').iteritems(): 
      # Should not get the value but bind a method 
      setattr(
       self, 
       user_method, 
       self.master.query(call) 
      ) 

    def get_user_id(self): 
     return self.user_id 


    def query(self, call): 
     return self.master(call) 

現在你可以看到它的設置直接執行該屬性的self.master.query(電話)時和已經結果是有當屬性被訪問。

問題是如何使這個屬性值在運行時動態化並且尚未執行?

我曾嘗試:

setattr(
       self, 
       user_method, 
       lambda: self.master.query(call) 
      ) 

但是,這並不出於某種原因工作。任何幫助/指導或最佳校長來實現所描述的結果?

+0

您能詳細說明「無法正常工作」嗎?函數沒有被調用嗎?你會得到一個異常,如果是的話,追溯是什麼? – user4815162342

+0

@ user4815162342不包含正確的結果。我認爲它包含了與第一個例子無關的東西。這是一個API調用,所以第一次執行,如果我這樣做:'''user.profile''工作正常,並有正確的數據,但使用lambda發佈最後的字典調用左右。我也很困惑。抱歉。 –

+0

@brunodesthuilliers有趣的一定是它。還有runkeeper。謝謝檢查儘快並報告 –

回答

3

這是一個衆所周知的疑難雜症。您必須在lambda中綁定您的論點的當前值,即:

setattr(
     self, 
     user_method, 
     lambda call=call: self.master.query(call) 
     ) 
+0

謝謝。而已! –