I want to store all the instances of a class in a list and want to iterate over it.
I have tried the following two approaches :
1 Using MetaClasses
class ClassIter(type):
def __iter__(cls):
return iter(cls._ClassRegistry)
def __len__(cls):
return len(cls._ClassRegistry)
class MyClass(object):
__metaclass__ = ClassIter
_ClassRegistry = []
def __init__(self,objname):
self._ClassRegistry.append(self)
self.name = objname
for x in ["first", "second", "third"]:
MyClass(x)
for y in MyClass:
print y.name
2 : Using iter in Class itself
class MyClass1(object):
_ClassRegistry = []
def __init__(self,objname):
self._ClassRegistry.append(self)
self.name = objname
def __iter__(self):
return iter(self._ClassRegistry)
for x in ["first", "second", "third"]:
MyClass1(x)
for y in MyClass1:
print y.name
Out of both the solutions, former approach works perfectly while the later solution gives an error TypeError: 'type' object is not iterable
.
Can some one please explain me (in detail) why the second approach is not working and why there is a need to use metaclass to make another class iterable?