This article uses simple examples to explain 「python The decorator 」.
「 The goal is 」 yes : After you read it , Can reach oneself 「 Write a simple decorator 」 The effect of !
Definition : The form of function is the form of function nested function , The internal function calls the variable value passed in by the external function , And the external function finally returns the reference of the internal function , Then the inner function is called 「 Closure 」
Take an example to explain
def outer(a):
b = 10
def inner():
print(a + b)
# The outer function returns a reference to the inner function
return inner
if __name__ == '__main__':
demo = outer(5)
print(demo) # <function outer.<locals>.inner at 0x000001EDAD6D88B8>
demo() # 15
Closure is introduced above , The external function receives a variable , If you take this variable -> Receive a reference to a function , Then it can be understood as a decorator
The main function of the decorator : Without changing the original function , Add some extra functionality to functions
Common applications of decorators : 「 Statistical function run time 」, 「 Login authentication 」 etc. . Pass below 2 An example briefly introduces
「 Decorator for counting function running time 」
import time
def collect_time(func):
def test():
t1 = time.time()
func()
t2 = time.time()
print(" Run at : ", t2 - t1)
return test
# Common writing
@collect_time
def run():
time.sleep(2)
if __name__ == '__main__':
run()
Briefly explain :
collect_time(run)()
collect_time(run)()
It means will run The reference to the function is passed to collect_time function , And then run collect_time(), Calculate the run time of the incoming function 「 Login authentication decorator - demo Example 」
def auth_user(func):
def auth_count(**kwargs):
username = kwargs["username"]
password = kwargs["password"]
if username == "lucy" and password == "12345":
verify = True
else:
verify = False
if verify:
return {"code": 200, "data": func(username), "msg": "login succ"}
else:
return {"code": 403, "msg": "login fail"}
return auth_count
@auth_user
def get_info(username="", password=""):
return {"username": username, "login_time": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}
if __name__ == '__main__':
# Normal use cases
print(get_info(username="lucy", password="12345"))
# Wrong use cases
# print(get_info(username="lucy", password="dfs"))
effect :
{'code': 200, 'data': {'username': 'lucy', 'login_time': '2022-01-18 12:26:00'}, 'msg': 'login succ'}
{"code": 403, "msg": "login fail"}
「 Code details - Login authentication decorator 」
get_info(username="lucy", password="12345")
when , Will get_info This function reference is passed as a parameter to auth_user function , return auth_count Function reference for username="lucy", password="12345"
The above is today's sharing about decorators