Defining Magic Methods On Classes
I would like to define a single object that can be iterated over without having to create a class and then an instance. Something like this: class Thing(object): stuff = ['foo'
Solution 1:
What Ashwini correctly suggested in his comment is the following. This works in Python 2.
classThingType(type):
__stuff__ = ["foo", "bar", "baz"]
@classmethoddef__iter__(cls):
returniter(cls.__stuff__)
classThing(object):
__metaclass__ = ThingType
for thing in Thing:
print thing
And this works in Python 3:
classThingType(type):
__stuff__ = ["foo", "bar", "baz"]
@classmethoddef__iter__(cls):
returniter(cls.__stuff__)
classThing(object, metaclass=ThingType):
passfor thing in Thing:
print(thing)
Solution 2:
Does Thing
actually need to be a type? You could make it an object that has type-like callable behavior, which would probably be simpler:
classRealThing(object):
passclassThingFactory(object):
def__iter__(self):
returniter(["foo", "bar", "baz"])
def__call__(self):
return RealThing()
Thing = ThingFactory()
Post a Comment for "Defining Magic Methods On Classes"