from collections.abc import Iterable
class Person(object):
def __init__(self, x):
self.x = x
self.count = 0
def __iter__(self):
return self # 只要重写了__iter__方法就是一个可迭代对象
def __next__(self):
# 每一次for...in循环都会调用一次
if self.count <10:
self.count +=1
return (self.x)
else:
raise StopIteration
p = Person(100)
print(isinstance(p, Iterable))
# for ...in的本质就是调用对象的__iter__方法,获取到这个方法的返回值
# 这个返回值是一个对象,然后再调用这个对象的__next__的方法
for x in p:
print(x)
使用迭代器生成斐波那契数列
import time
class Function(object):
def __init__(self,n):
self.num1, self.num2 = 1, 1
self.count = 0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.count<self.n:
self.count+=1
x = self.num1
self.num1, self.num2 = self.num2, self.num1 + self.num2
return x
else:
raise StopIteration
f =Function(12)
for k in f:
print(k)
with关键字
# with open("异常处理.py",'r',encoding='utf') as file:
# print(file.read()) # 不需要手动关闭文件,with关键字会帮助我们关闭文件
try:
with open('异常处理.py','r',encoding="utf8") as file:
print(file.read())
except FileNotFoundError as e:
print(e+"文件找不到")
# with我们称之为上下文管理器,很多需要手动关闭的连接
# 比如 文件连接,socket连接,数据库的连接,都能使用with关键字关闭连接
# with关键字后面对象,要实现__enter__和__exit__魔法方法
finally的注意事项
# 一个函数最多只有一个return语句返回
def demo(a, b):
try:
x = a / b
except ZeroDivisionError as e:
print(e)
else:
return x
finally:
return 'good' # 如果函数里面有finally,finally里的返回值会覆盖之前的反回值
print(demo(2, 5)) # good
异常处理
# 健壮性:很多编程语言都有异常处理机制
def div(a, b):
return a / b
try:
x = div(5, 2)
file = open('ddd.txt')
print(file.read())
file.close()
# except Exception as e 给异常起了一个变量名
# except Exception as e: # 如果程序出错了,会立刻跳转到except语句
# print("程序出错了")
except (FileNotFoundError,ZeroDivisionError) as e: # 处理指定类型的异常
print(e)
else:
print(x) # 只要执行了except语句,就把不会执行else语句