我继承了一个包含许多大型类的项目,这些类仅由类对象(整数、字符串等)组成。我希望能够检查属性是否存在,而无需手动定义属性列表。
是否可以制作一条蟒蛇classiterable 本身使用标准语法?也就是说,我希望能够使用迭代所有类的属性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
Add the __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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)