将__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