I have defined the following class
class Person(object):
_counter = 0
_instances = []
def __init__(self, nam):
self.name = nam
self._instances.append(self)
self._id = Person._counter + 1
Person._counter+=1
def __repr__(self):
return f'{self._id} : Person({self.name})'
def __iter__(self):
return self
def __next__(self):
pass
@classmethod
def iterate(cls):
return [p for p in Person._instances]
I can iterate over the instances of this class with
[p for p in Person._instances]
I would like to learn how it is possible to arrive at the same result by calling
[p for p in Person]
I have searched many similar questions and I tried out several suggested answers, without any luck. I am using Python 3.6 Anaconda x64 and in all the solutions I tested on the interpreter I am getting back
[p for p in Person]
TypeError: 'type' object is not iterable
Could you please write exactly how I can execute successfully this [p for p in Person] call to get back the same list as Person.iterate() and Person._instances ?
You can define an __iter__ on the metaclass to make the metaclass instance (i.e. Person) iterable:
class metaclass(type):
def __iter__(cls):
return iter(getattr(cls, '_instances', []))
class Person(metaclass=metaclass):
# __metaclass__ = metaclass Python 2
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With