table of Contents
Closure function
Closure function: the functions and variables wrap
def make_averager():
series = []
def averager(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return averager
avg = make_averager()
print(avg(10))
print(avg(20))
print(avg(30))
10.0
15.0
30.0
Decorator
Decorator is a function
Two principles:
- Without changing the source code of the function to be decorated
- Do not change the function calls are decorated
def deco(func):
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
print("I'm Tiny")
return res
return wrapper
@deco
def say(x):
print(f'Hello,{x}')
return 'Nice to meet you'
say = say('nick')
print(say)
Above the decorator, the last call say () when, in fact, is calling wrapper (), if say () returns a value, then the wrapper () inside also need to return this value, that is, above the res
If you say () need to pass parameters, then the wrapper () should be passed within the same parameters, but because we do not know what to say parameters passed (), all can use * args, ** kwargs universal parameters to represent
python decorator syntax sugar
In the decorative function just above, and is written on a separate line@装饰器名
You can call the function directly be decorated
Three decorator
import time
current_uesr = {'username': None}
def auth(engine='file'):
def login(func):
# func = 最原始的index
def wrapper(*args, **kwargs):
if current_user['username']:
res = func(*args, **kwargs)
return res
user = input('username: ').strip()
pwd = input('password: ').strip()
if engine == 'file':
print('base of file')
if user == 'nick' and pwd == '123':
print('login successful')
current_uesr['usre'] = user
res = func(*args, **kwargs)
return res
else:
print('user or password error')
elif engine == 'mysql':
print('base of mysql, please base of file')
elif engine == 'mongodb':
print('base of mongodb, please base of file')
else:
print('please base of file')
return wrapper
return login
@auth(engine='mysql')
def home(name):
print(f"welcome {name} to home page")
time.sleep(1)
@auth(engine='file')
def index():
print('welcome to index')
time.sleep(1)
res = index()
username: nick
password: 123
base of file
login successful
welcome to index