Given a class that keeps a registry of its Objects:
class Person(object):
__registry = []
def __init__(self, name):
self.__registry.append(self)
self.name = name
How would I make the following code work (without using Person.__registry):
for personobject in Person:
print personobject
While researching I found a hint that one could go for a __metaclass__ with a __getitem__-method. Any ideas how this would look like?
解决方案
You can make your class object iterable with a simple metaclass.
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
class Person(object):
__metaclass__ = IterRegistry
_registry = []
def __init__(self, name):
self._registry.append(self)
self.name = name
(I have also changed __registry to _registry to make it easier to access from the metaclass).
Then,
>>> p = Person('John')
>>> p2 = Person('Mary')
>>> for personobject in Person:
... print personobject
...