我继承了一个项目,其中包含许多大型类,这些类仅由类对象(整数、字符串等)组成。我希望能够检查属性是否存在,而无需手动定义属性列表。
是否可以使用标准语法使 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/