python装饰器,迭代,异常
装饰器的联系
DEL = 8
READ = 4
WRITE = 2
EXE = 1
userpermission = 9
def check(x, y):
print("最外层函数被调用了")
def handle(fn):
print("handle函数被调用了")
def do_ction():
if x & y != 0:
fn()
return do_ction
return handle
@check(userpermission, READ)
def read():
print("可以读")
@check(userpermission, DEL)
def _del():
print("可以删除")
@check(userpermission, WRITE)
def _write():
print("可以写")
@check(userpermission, EXE)
def exe():
print("可以运行")
read()
_del()
_write()
exe()
高级装饰器
def can_play(clock=12):
print("最外层函数被调用了,clock={}".format(clock))
def handle_action(fn):
print("handle_action被调用了")
def do_action(x,y):
print(x,y)
if clock>23:
print("太晚了,不能玩游戏了")
else:
fn(x,y)
print("可以玩游戏")
return do_action
return handle_action
@can_play(22)
def play(name, game):
print(name + "正在玩" + game + "游戏")
play("张三", "王者荣耀")
可迭代对象
from collections.abc import Iterable
class Person(object):
def __init__(self, x):
self.x = x
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count <10:
self.count +=1
return (self.x)
else:
raise StopIteration
p = Person(100)
print(isinstance(p, Iterable))
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关键字
try:
with open('异常处理.py','r',encoding="utf8") as file:
print(file.read())
except FileNotFoundError as e:
print(e+"文件找不到")
finally的注意事项
def demo(a, b):
try:
x = a / b
except ZeroDivisionError as e:
print(e)
else:
return x
finally:
return 'good'
print(demo(2, 5))
异常处理
def div(a, b):
return a / b
try:
x = div(5, 2)
file = open('ddd.txt')
print(file.read())
file.close()
except (FileNotFoundError,ZeroDivisionError) as e:
print(e)
else:
print(x)
自定义异常
class MyError(Exception):
def __init__(self):
print("密码长度不正确")
if __name__ == '__main__':
password = input('请输入密码:')
if 12 >= len(password) >= 6:
print("密码正确")
else:
raise MyError
上下文管理器
class Demo(object):
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def create_obj():
x =Demo()
return x
with create_obj() as d:
print(d)
|