【问题标题】:How to iterate on self attributes inside a class in Python3?如何在 Python3 中的类中迭代自身属性?
【发布时间】:2017-05-30 06:05:14
【问题描述】:

我想从 Python3 中的 self 函数中迭代 self 属性,但我没有找到任何类似的。我发现了如何在课堂之外做到这一点here

我的问题是,有可能吗?

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

【问题讨论】:

  • 你想遍历attr1attr2
  • 是的,themiurge 和 Gustavo 在下面评论正确答案。

标签: python python-3.x


【解决方案1】:

您可以通过__dict__ 成员访问所有属性:

class Foo:

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

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

您也可以使用vars(感谢 Azat Ibrakov 和 S.M.Styvane 指出这一点):

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

Here 是关于 __dict__vars() 的一个很好的讨论。

【讨论】:

  • 你可以简单的sum(self.__dict__.values())
  • 或使用vars:sum(vars(self).values())
【解决方案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

【讨论】:

  • 正确,效果很好。但是,有什么区别?性能,也许?
  • 在其他回复中,themiurge 链接此discussion
猜你喜欢
  • 2019-10-07
  • 2016-06-30
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
相关资源
最近更新 更多