在 类 上定义魔法方法
Defining magic methods on classes
我想定义一个可以迭代的单个对象,而无需创建 class 然后再创建一个实例。像这样:
class Thing(object):
stuff = ["foo", "bar", "baz"]
@classmethod
def __iter__(cls):
return iter(cls.stuff)
for thing in Thing:
print thing
但这实际上不起作用。有什么办法吗?
Thing
真的需要类型吗?您可以使它成为具有类类型可调用行为的对象,这可能会更简单:
class RealThing(object):
pass
class ThingFactory(object):
def __iter__(self):
return iter(["foo", "bar", "baz"])
def __call__(self):
return RealThing()
Thing = ThingFactory()
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)
我想定义一个可以迭代的单个对象,而无需创建 class 然后再创建一个实例。像这样:
class Thing(object):
stuff = ["foo", "bar", "baz"]
@classmethod
def __iter__(cls):
return iter(cls.stuff)
for thing in Thing:
print thing
但这实际上不起作用。有什么办法吗?
Thing
真的需要类型吗?您可以使它成为具有类类型可调用行为的对象,这可能会更简单:
class RealThing(object):
pass
class ThingFactory(object):
def __iter__(self):
return iter(["foo", "bar", "baz"])
def __call__(self):
return RealThing()
Thing = ThingFactory()
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)