一个对象可以通过for循环来遍历,这种遍历我们称为迭代(Iteration)。
例如以下代码:
class Animal(object):
def __init__(self, name):
self.name = name
a1 = Animal("panda")
for one in a1:
print one
执行时出现如下错误:
Traceback (most recent call last):
File “test.py”, line 16, in <\module>
for one in a1:
TypeError: ‘Animal’ object is not iterable
解决办法:
需要为类定义__iter__方法以及next方法,使之可迭代。
class Animal(object):
def __init__(self, name):
self.name = name
self.age = 12
self._i = 0
def __iter__(self):
return self
def next(self):
if self._i == 0:
self._i += 1
return self.name
elif self._i == 1:
self._i += 1
return self.age
else:
raise StopIteration()
a1 = Animal("panda")
for one in a1:
print one
output:
panda
12
再次执行时,for循环依次打印a1对象的属性。