问题
我希望能够像枚举一样在不实例化类型的情况下迭代它。
class Foo:
"""Class I want to iterate over without instantiating."""
ALLOWED_VALUES = (1, 2, 3)
# I want iterating over `Foo` to be equivalent to iterating over `Foo.ALLOWED_VALUES`
for val_from_tuple, val_from_foo in zip(Foo.ALLOWED_VALUES, Foo):
assert val_from_tuple == val_from_foo
这种行为可以使用枚举实现,但只有在ALLOWED_VALUES是有效的Python名称时才能实现。我希望在没有这个限制的情况下具有相同的迭代行为。
我尝试过的方法
我尝试将__iter__()实现为Foo上的一个staticmethod,这样就不需要一个Foo实例来获取其迭代器。这使我能够遍历Foo.__iter__(),但iter(Foo)会引发错误。这似乎是因为iter(Foo)在type上查找__iter__方法,而不是在Foo上查找__iter__方法(因为Foo是一个type对象)。class Foo:
"""Class I want to iterate over without instantiating."""
ALLOWED_VALUES = (1, 2, 3)
@staticmethod
def __iter__():
return Foo.ALLOWED_VALUES
# This works, but isn't what I want because it involves calling `__iter__()` explicitly.
for val in Foo.__iter__():
print(val)
# This raises an error:
# `TypeError: 'type' object is not iterable`
for val in Foo:
print(val)
self
参数命名为cls
,以提醒读者它正在处理一个类对象。 - user4815162342