2017-05-30 57 views
0

我想在Python3中自我函數的自我屬性迭代,但我還沒有找到任何類似的東西。我發現如何在課堂上做here如何迭代Python3中的類中的自我屬性?

我的問題是,這可能嗎?

class Foo: 

    def __init__(self, attr1, attr2): 
     self.attr1 = attr1 
     self.attr2 = attr2 

    def method1(self): 
     #Return sum of the values of the self attributes 
     pass 
+0

通過'attr1','attr2'? –

+0

是的,themiurge和Gustavo評論下面的正確答案。 –

回答

2

我不喜歡簡單的事情使用__dict__。您應該使用vars來回報您的實例的屬性字典

要遍歷
>>> class Foo(object): 
...  def __init__(self, attr1, attr2): 
...   self.attr1 = attr1 
...   self.attr2 = attr2 
...  def method1(self): 
...   return sum(vars(self).values()) 
... 
>>> Foo(2, 4).method1() 
6 
+0

這是正確的,精細。但是,有什麼區別?性能,也許? –

+0

在其他回覆themiurge鏈接這[討論](https://stackoverflow.com/questions/21297203/use-dict-or-vars)。 –

4

您可以通過__dict__成員訪問所有的屬性:

class Foo: 

    def __init__(self, attr1, attr2): 
     self.attr1 = attr1 
     self.attr2 = attr2 

    def method1(self): 
     return sum(self.__dict__.values()) 

您還可以使用vars(感謝阿扎特Ibrakov和SMStyvane指出這一點):

def method1(self): 
     return sum(vars(self).values()) 

Here__dict__vars()之間是一個很好的討論。

+2

你可以簡單地使用'sum(self .__ dict __。values())' –

+1

你是對的,我會修復它! – themiurge

+0

是的,這工作正常。非常感謝。 –