如何在Python3中迭代类内的自属性?
我想在Python3中的self函数中迭代self属性,但我没有发现任何类似的。我在课外找到了做这件事的方法 我的问题是,这可能吗如何在Python3中迭代类内的自属性?,python,python-3.x,Python,Python 3.x,我想在Python3中的self函数中迭代self属性,但我没有发现任何类似的。我在课外找到了做这件事的方法 我的问题是,这可能吗 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
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
您可以通过_dict__成员访问所有属性: 感谢Azat Ibrakov和S.M.Styvane指出这一点:
def method1(self):
return sum(vars(self).values())
这是一个很好的关于“dict”与“vars”的讨论。我不太喜欢将dict用于简单的事情。您应该使用vars返回实例属性的dict
>>> 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
你想重复使用attr1、attr2?是的,Miurge和Gustavo评论下面的正确答案。你可以简单地使用sumself.\uuu dict\uuuuuu.values或use:sumvarsself.values这是正确的,效果很好。但是,有什么区别呢?性能,也许?在其他回应中,Miurge将此链接。
>>> 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