据我所知,通过使用元类使类对象变得可iterable工作得很好:from __future__ import print_function
class IterableCar(type):
def __iter__(cls):
return iter(cls.__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)
结果:mgilson$ python ~/sandbox/test.py
C
a
r
下面是一个我实际跟踪生成的汽车的示例:from __future__ import print_function
import weakref
class IterableCar(type):
_cars = weakref.WeakSet()
def __iter__(cls):
return iter(cls._cars)
def add_car(cls, car):
cls._cars.add(car)
class Car(object):
__metaclass__ = IterableCar
def __init__(self, name):
self.__class__.add_car(self)
self.name = name
if __name__=='__main__':
car1 = Car('Mercedes')
car2 = Car('Toyota')
for cars in Car:
print (cars.name)
请注意,如果使用python3.x,要使用元类,需要执行以下操作:class Car(metaclass=IterableCar):
...
而不是:class Car(object):
__metaclass__ = IterableCar
这可能解释了你正在经历的问题。