软件面世时,不可能把所有的功能都设计好,当前的未来一两年功能给你上线,定期更新迭代。对于软件之前的写的源代码一般都不会修改,对函数里面的代码以及函数的调用方式。
开放原则
:在源码不改变的情况下,增加一些额外的功能。
def warpper(f):#装饰器名
def inner(*args,**kwargs):
#被装饰之前执行的操作
ret=f(*args,**kwargs)#执行原函数
#被装饰之后执行的操作
return ret#原函数的返回值
return inner
@warpper#func=warpper(func)
def func():
print(1)
def warrper_out(n):#最外层传入参数
def warrper(f):#标准装饰器写法
def inner(*args,**kwargs):
with open(n,mode="r",encoding="utf-8")as f1:#这里的n就是调用的传进来的参数
dic={}
for i in f1:
i=i.strip().split("|")
dic[i[0]]=i[1]
username=input("name:").strip()
psw=input("psw:").strip()
if dic.get(username) and psw==dic[username]:
ret=f(*args,**kwargs)
else:
print("失败")
return ret
return inner
return warrper
@warrper_out("qq")
# 1. 执行wrapper_out('qq') 这个函数,把相应的参数'qq' 传给 n,并且得到返回值 wrapper函数名。
# 2. 将@与wrapper结合,得到我们之前熟悉的标准版的装饰器按照装饰器的执行流程执行。
def qq():
print("欢迎登录qq")
qq()
@warrper_out("dy")
def dy():
print("欢迎来到抖音")
dy()
# def wrapper1(func1): # func1 = f原函数
# def inner1():
# print('wrapper1 ,before func') # 2
# func1()
# print('wrapper1 ,after func') # 4
# return inner1
#
# def wrapper2(func2): # func2 == inner1
# def inner2():
# print('wrapper2 ,before func') # 1
# func2() # inner1
# print('wrapper2 ,after func') # 5
# return inner2
#
#
# @wrapper2 # f = wrapper2(f) 里面的f == inner1 外面的f == inner2
# @wrapper1 # f = wrapper1(f) 里面的f == func1 外面的 f == inner1
# def f():
# print('in f') # 3
#这里也可以理解为wrapper2装饰了wrapper1,所以其中的func2相当于wrapper1
#wrapper1装饰了原函数f,wrapper1中的func1就是原函数
#
# f() # inner2()
原文:https://www.cnblogs.com/nieice/p/11106582.html