1. 重点
- 必须要在类里定义一个
__iter__
方法 __iter__
方法,必须返回一个迭代器(注意生成器也是迭代器的一种)
2. 普通对象执行for循环
代码
class Student():
name = 'tom'
age = 18
hobby = ['baskball','football']
obj = Student()
for i in obj:
print(i)
执行结果
Traceback (most recent call last):
File "/Users/mal/一个对象怎样才能被执行for循环.py", line 21, in <module>
for i in obj:
TypeError: 'Student' object is not iterable
3. 定义了iter方法对类
代码
class Student():
name = 'tom'
age = 18
hobby = ['basktball','football']
# 1. 必须定义一个iter方法
def __iter__(self):
# 2. 必须返回一个迭代器(注意:生成器也是迭代器的一种)
return iter([self.name,self.age,self.hobby])
obj = Student()
for i in obj:
print(i)
执行结果
tom
18
['basktball', 'football']