程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python decorator, right here?

編輯:Python

Preface

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 !

Closure

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
  1. First 「 Function reference 」 It can be simply understood as function address ( similar go The pointer in ). stay python Can be simply understood as , Use 「 Function reference ()」 You can run the function corresponding to the function address
  2. Use demo = outer(5) after , demo That is to say inner References to functions . And then use demo(), It is equivalent to using inner().
  3. inner Function received an external incoming a=5, And internally defined local variables b=10, The final output 15

Decorator

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 :

  1. In the above run Add... To the function @collect_time Writing , amount to collect_time(run)()
  2. 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 :

  • Enter the correct user name + password , Return the response information of successful login , for example :
{'code': 200, 'data': {'username': 'lucy', 'login_time': '2022-01-18 12:26:00'}, 'msg': 'login succ'}
  • Wrong user name or password , Return the response information of login failure , for example :
{"code": 403, "msg": "login fail"}

「 Code details - Login authentication decorator 」

  1. call 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
  2. Then run auth_count function , The parameters received by this function are username="lucy", password="12345"
  3. auth_count Function defines a variable parameter in the form of a dictionary **kwargs, Then get... From the passed in parameters username and password
  4. auth_count The function is internally based on the parsed username and password To determine whether it is correct . If it is correct, the login information of the user will be returned ; Wrong words , Just go back to 403 Of error Information

The above is today's sharing about decorators


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved