假设我们有以下类:
class Klass:
iterable_attr_names = {'x', 'y', 'z'}
x = 5
y = 6
z = 7
def __init__(self):
pass
def foo(*args): # 'foo' is not in iterable_attr_names
return
是否可以为类定义__iter__
方法,而不仅仅是类的实例?类__iter__
方法的实现可能如下所示:
class KlassIter:
def __init__(self, klass):
self._klass = klass
self._inner_it = iter(klass.iterable_attr_names)
def __next__(self):
attr_name = next(self._inner_it)
return getattr(self._klass, attr_name)
然后我们可以这样做:
print(Klass.x)
print(Klass.y)
print(Klass.z)
和此:
for attr in Klass:
print(attr)