from collections.abc import Iterable
classPerson(object):def__init__(self, x):
self.x = x
self.count =0def__iter__(self):return self # 只要重写了__iter__方法就是一个可迭代对象def__next__(self):# 每一次for...in循环都会调用一次if self.count <10:
self.count +=1return(self.x)else:raise StopIteration
p = Person(100)print(isinstance(p, Iterable))# for ...in的本质就是调用对象的__iter__方法,获取到这个方法的返回值# 这个返回值是一个对象,然后再调用这个对象的__next__的方法for x in p:print(x)
使用迭代器生成斐波那契数列
import time
classFunction(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:withopen('异常处理.py','r',encoding="utf8")asfile:print(file.read())except FileNotFoundError as e:print(e+"文件找不到")# with我们称之为上下文管理器,很多需要手动关闭的连接# 比如 文件连接,socket连接,数据库的连接,都能使用with关键字关闭连接# with关键字后面对象,要实现__enter__和__exit__魔法方法
finally的注意事项
# 一个函数最多只有一个return语句返回defdemo(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
异常处理
# 健壮性:很多编程语言都有异常处理机制defdiv(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语句
# with语句后面的结果对象,需要重写__enter__和__exit__方法# 当进入with代码块时,会自动调用__enter__方法里的代码# 当with代码块执行完以后,会自动调用__exit__方法classDemo(object):def__enter__(self):passdef__exit__(self, exc_type, exc_val, exc_tb):passdefcreate_obj():
x =Demo()return x
with create_obj()as d:# as 变量名# 变量d不是create_obj的返回结果# 它是创建的对象x调用__enter__之后的返回结果print(d)