Python:使类可迭代

标签 python syntax attributes static-methods loops

我继承了一个项目,其中包含许多大型类,这些类仅由类对象(整数、字符串等)组成。我希望能够检查属性是否存在,而无需手动定义属性列表。

是否可以使用标准语法使 python 自身可迭代?也就是说,我希望能够使用 for attr in Foo:(甚至 if attr in Foo)遍历一个类的所有属性,而无需创建首先是类的一个实例。我想我可以通过定义 __iter__ 来做到这一点,但到目前为止我还没有完全管理我正在寻找的东西。

我通过添加一个 __iter__ 方法实现了一些我想要的,如下所示:

class Foo:
    bar = "bar"
    baz = 1
    @staticmethod
    def __iter__():
        return iter([attr for attr in dir(Foo) if attr[:2] != "__"])

但是,这并不能完全满足我的要求:

>>> for x in Foo:
...     print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'classobj' object is not iterable

即便如此,这仍然有效:

>>> for x in Foo.__iter__():
...     print(x)
bar
baz

最佳答案

__iter__ 添加到元类而不是类本身(假设 Python 2.x):

class Foo(object):
    bar = "bar"
    baz = 1
    class __metaclass__(type):
        def __iter__(self):
            for attr in dir(self):
                if not attr.startswith("__"):
                    yield attr

对于 Python 3.x,使用

class MetaFoo(type):
    def __iter__(self):
        for attr in dir(self):
            if not attr.startswith("__"):
                yield attr

class Foo(metaclass=MetaFoo):
    bar = "bar"
    baz = 1

关于Python:使类可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49419367/

相关文章:

python - 在特定键值处开始字典 for 循环

python - 将字符串右分成 3 组

VB.NET 中括号 () {} [] <>

sql - tSQL CASE 控制执行

Python:如何使对象属性引用调用方法

python - 如何使用循环在数据帧中逐行读取并返回每个值或弹出每个值

optimization - 为什么大多数语言不能优化 “0 * …”,并且有任何语言可以优化?

c# - 访问自定义属性的值

C# 允许派生类的多个属性

python - Django 查询集与 distinct 和 exclude 一起