我想定义一个可以迭代的单个对象,而不必先创建一个类,然后再创建一个实例。像这样:
class Thing(object):
stuff = ["foo", "bar", "baz"]
@classmethod
def __iter__(cls):
return iter(cls.stuff)
for thing in Thing:
print thing
但是,这实际上不起作用。有什么办法吗?
以下是Ashwini在其评论中正确建议的内容。这适用于Python 2。
class ThingType(type):
__stuff__ = ["foo", "bar", "baz"]
@classmethod
def __iter__(cls):
return iter(cls.__stuff__)
class Thing(object):
__metaclass__ = ThingType
for thing in Thing:
print thing
这适用于Python 3:
class ThingType(type):
__stuff__ = ["foo", "bar", "baz"]
@classmethod
def __iter__(cls):
return iter(cls.__stuff__)
class Thing(object, metaclass=ThingType):
pass
for thing in Thing:
print(thing)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句