I am working on a project and I would like to make one of my classes iterable. To the best of my knowledge I can do that with using metaclass.
First of all I would like to understand how metaclass works. Therefore I would like to present my own practicing example where I made a Car class. So here I would like to make my Car class objects iterable then I would like to print the names of them in the main function.
The code example is the following:
__author__ = 'mirind4'
class IterableCar(type):
def __iter__(self):
return iter(self.__name__)
class Car(object):
__metaclass__ = IterableCar
def __init__(self, name):
self.name = name
if __name__=='__main__':
car1 = Car('Mercedes')
car2 = Car('Toyota')
for cars in Car:
print (cars.name)
But unfortunately I got an TypeError:
TypeError: 'type' object is not iterable
Would you be so kind as to tell me where I do the mistake in my code? So far I have checked similar problem-questions over this site and internet but I do not know what the problem is. I am using python 3.4. Thanks in advance!
for cars in Car
. Car is a class definition. What do you expect that to do? Did you mean to putcar1
andcar2
into a list and iterate over that? (I see that you have something at the top of your question about "making a class iterable" but it's not clear what you want.Car
doesn't seem to represent any kind of collection.) – TenderloinC - A - R
... Interesting concept making an iterable class... – Gurtnerclass Car(metaclass=IterableCar)
, not with the__metaclass__
attribute. – Avisavitaminosis__new__
method. – Avisavitaminosis__new__
, I believe so. – Avisavitaminosis