1 开放封闭原则
- 拓展是开放的 (增加新功能)
- 修改源码是封闭的 (修改已经实现的功能)
在不改变源代码及调用方式的基础上额外增加新的功能
2 装饰器 (用来装饰的工具)
2.1标准版装饰器:
def wrapper(func):
def inner(*args,**kwargs):
'''执行被装饰函数之前的操作'''
ret = func(*args,**kwargs)
'''执行被装饰函数之后的操作'''
return ret
return inner
语法糖: 必须放在被装饰的函数正上方
import time
def times(f):
def inner():
start_time = time.time()
ret = f()
end_time = time.time()
print(end_time - start_time)
return ret
return inner
@times #相当于foo = times(foo)
def foo():
time.sleep(3) #模拟网络延迟
print('111')
# foo = times(foo)
foo()
2.2带参数的装饰器
def auth(argv):
def wrapper(f):
def inner():
ret = f()
if argv == 'QQ':
print('QQ登陆成功!')
elif argv == '微信':
print('微信登录成功!')
else:
print('邮箱登陆成功!')
return inner
return wrapper
choose = input('>>>')
@auth(choose)
def func():
pass
func()
2.3多个装饰器装饰一个函数
def wrapper1(f): # f = inner2
def inner1(*args,**kwargs):
print(1)
ret = f(*args,**kwargs)
print(11)
return ret
return inner1
def wrapper2(f): # f = inner3
def inner2(*args,**kwargs):
print(2)
ret = f(*args,**kwargs)
print(22)
return ret
return inner2
def wrapper3(f): # f = func
def inner3(*args,**kwargs):
print(3)
ret = f(*args,**kwargs)
print(33)
return ret
return inner3
@wrapper1
@wrapper2
@wrapper3
def func():
print(4)
func()
func = wrapper3(func) # func = inner3
func = wrapper2(func) # inner2 = wrapper2(inner3)
func = wrapper1(func) # inner1 = wrapper1(inner2)
func() #inner1()