06.01 self-summary
A. Decorator
1. The function defined in the bezel
A decorative function Function: a function of decorator
2. Personal understanding two function decorator
Two function decorator personally think he really needs is to decorate the function name thrown into the parameter, then use a nested function 对其头尾
to add programs, but can not reduce the content of his program, he can only change the original program 增不能减少
, then functions return a good decoration, and then define a global variable name to be decorated with the same name as the function name and function call after the decoration given amount of change.
1. Simple examples (a non-parametric function)
Such as
#有个函数f1
def f1():
print('nick machachong')
#我们要对齐装饰使其输出打印内容上下都加了'-'线
def f1_deco(f1): #第一步吧变量丢进去
def wrapper():
#print(50*'-') #我们加的内容
#print('nick machachong') #这个等同于f1()
#print(50*'-') #我们要加的内容
#这是我们需要的打印效果
pritn(50*'-')
f1()
print(50*'-')
return wrapper
f1 = f1_deco(f1) #前面的f1是变量f1,函数本是f1并未发生变化只是一个变量名接受了f1
f1()
```
--------------------------------------------------
nick machachong
--------------------------------------------------
```
#另外种写法
@f1_deco
def f1():
print('nick machachong')
f1()
```
--------------------------------------------------
nick machachong
--------------------------------------------------
```
2. There are about function parameters
#如函数
def sum(x,y):
print(x+y)
#我们要对齐装饰使其输出打印内容上下都加了'-'线
def sum_deco(sum):
def wrapper(x,y):
print("-")
sum(x,y)
return sum
sum() = sum_deco(sum)
sum(x,y)
#多个值
def sb(x,y,z=2,b=1):
print(x,y,z,b)
#把他进行封装
def sb_deco(sb):
def wrapper(*args,**kwargs):
print('nick machachong')
sb(*args,**kwargs)
return wrapper
sb = sb_deco(sb)
sb(1,23,2,3)
3. For the function returns a value of formula
#有返回值
def sb(x,y,z=2,b=1):
return x,y,z,b
#对于返回值乘以3
def sb_deco(sb):
def wrapper(*args,**kwargs):
res = sb(*args,**kwargs)
res = list(res)
for a in range(len(res)):
res[a] = 3*res[a]
res = tuple(res)
return res
return wrapper
sb = sb_deco(sb)
print(sb(2,3,4,5))
4. decorative circle template
def sb(*args,**kwargs):
pass
#装饰器模板
def sb_deco(sb):
def wrapper(*args,**kwargs):
#sb(*args,**kwargs)
res = sb(*args,**kwargs) #赋值的时候已经开始调用了所有没必要在写一步调用
return res
return wrapper
sb = sb_deco(sb)
sb(1,23,2,3,12,312,312,3,123)
3. For three decorators understand
#比如说一个函数为,我们对齐装饰,打印内容前后上下加'-'
def sb():
print('i am sb')
#装饰
def sb_deco(sb):
def wrapper():
print('-'*5)
sb()
print('-'*5)
return wrapper
#只时候我们加条件要区分是你输入还是我输入的
# 只时候我们加条件要区分是你输入还是我输入的, 我那边聪明肯定不是SB
def sb_deco(sb):
def wrapper():
if user == 'you':
print('-' * 5)
sb()
print('-' * 5)
elif user == 'i':
print('-' * 5)
sb()
print('这是不可能的')
print('-' * 5)
return wrapper
#这时候我们导入的参数多了个user
def user(user):
def sb_deco(sb):
def wrapper():
if user == 'you':
print('-' * 5)
sb()
print('-' * 5)
elif user == 'i':
print('-' * 5)
sb()
print('这是不可能的')
print('-' * 5)
return wrapper
return sb_deco
@user('you') #其中@user('you') 相当于a =user('you') sb = a(sb)
def sb():
print('i am sb')
sb()
#他是对于输入的值的一层装饰,判断他是拿来的
`