我继承了一个包含许多大类的项目,这些大类仅由类对象(整数,字符串等)组成。我希望能够检查是否存在属性,而无需手动定义属性列表。
是否可以使用标准语法使其本身可迭代的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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句