python基础教程第二版 9 :魔法方法,属性,迭代器
新类与旧类
构造方法:对象被创建后立即执行的方法 __init__
class 类名:
def __init__(self):
self.属性=值
每个类都可以有多个超类,它们从超类那里继承方法.
9.7 生成器
生成器是一种用普通的函数语法定义的迭代器.
任何包含yield的函数都是生成器.每次使用yield产生一个值,函数就会被冻结:即函数停在那个点等待被激活.
yield语句意味着生成一个值,return语句意味着要停止执行(也只有在生成器中可以不加参数调用.)
生成器包括2部分:生成器的函数和生成器的迭代器.
函数是def定义的部分,迭代器是函数返回的部分.
迭代器可以执行迭代操作.
def func(list):
for sublist in list:
for i in sublist:
yield i
A=[[1,2],[3,4],[5]]
print(func(A))
for a in func(A):
print a
print(list(func(A)))
结果
1
2
3
4
5
[1, 2, 3, 4, 5]
def func(list):
for sublist in list:
# for i in sublist:
# yield i
yield sublist
A=[[1,2],[3,4],[5]]
print(func(A))
for a in func(A):
print a
print(list(func(A)))
结果
[1, 2]
[3, 4]
[5]
[[1, 2], [3, 4], [5]]
def func(list):
for sublist in list:
for i in func(sublist):#取出的元素类型不一定是列表,所以要处理异常
yield i
A=[[1,2],[3,4],[5,[6,7]]]
print(func(A))
for a in func(A):
print a
print(list(func(A)))
结果
Traceback (most recent call last):
File "/home/talen/PycharmProjects/untitled/test.py", line 7, in
for a in func(A):
File "/home/talen/PycharmProjects/untitled/test.py", line 3, in func
for i in func(sublist):
File "/home/talen/PycharmProjects/untitled/test.py", line 3, in func
for i in func(sublist):
File "/home/talen/PycharmProjects/untitled/test.py", line 2, in func
for sublist in list:
TypeError: 'int' object is not iterable
def func(list):
try:
for sublist in list:
for i in func(sublist):
yield i
except TypeError:
yield list
A=[[1,2],[3,4],[5,[6,7]],8]
print(list(func(A)))
结果
[1, 2, 3, 4, 5, 6, 7, 8]
#字符串被看成原子值,不应该被迭代
def func(list):
try:
try:
list+''
except TypeError:pass
else:
raise TypeError
for sublist in list:
for i in func(sublist):
yield i
except TypeError:
yield list
A=[[1,2],[3,4],[5,[6,7]],8,'abc']
print(list(func(A)))
结果:
[1, 2, 3, 4, 5, 6, 7, 8, 'abc']
阅读(1202) | 评论(0) | 转发(0) |