Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use decorator in python

Shulou Source: shulou.com Published: 2022-06-02 07:10:24 10月20日 Update

This article shows you how to use the decorator in python. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Structure of decorator with parameters

Everyone knows that the decorator is used to expand the function, but don't forget that the decorator itself is also a function, of course, you can also expand the function by adding parameters to the decorator.

Let's continue yesterday's case with parameter decorator: now the customer has raised the demand again, and the customer finds that the accounts of the cash register are clear from Monday to Friday, but the accounts are a little messy on Saturday and Sunday. Customers want the cash register to keep all transactions on Saturday and Sunday in a log file, and transactions from Monday to Friday do not need to be saved.

Analyze customer requirements, according to the contents of the decorator we learned yesterday, we can quickly come up with a solution, and then write a decorator to keep transaction records. But there is a difficulty here. What if the customer asks not to save it from Monday to Friday and on Saturday and Sunday?

Here, you need to use the decorator with parameters. The specific code is as follows:

Import functoolsfrom datetime import datetime# this line of code is to get the current day of the week, Monday corresponds to 1, Saturday corresponds to 6, Sunday corresponds to day_week = datetime.now (). Isoweekday () # Today is Tuesday, tomorrow Wednesday, will not trigger logging conditions, temporary comments, easy to test day_week = Sunday for testing, assuming today is Sunday. Comment this line in actual use and uncomment the above line. Def check_week (chk): def inner (func): @ functools.wraps (func) def inner_chk (* args, * * kwargs): if chk: with open ('log.txt', mode='a', encoding='utf8') as f: f.write (f' transaction: discount value is {args [0]}, commodity unit price {args [1]} Quantity of goods {args [2]}, trading time is {datetime.now ()}\ n') return func (* args, * * kwargs) return inner_chk return innerdef checkdisct (func): @ functools.wraps (func) def inner (* args, * * kwargs): disct = args [0] if disct > = 0.5and disct

Tags: Parameters functions transactions goods passwords customers discounts functions logs time conditions tests code comments requirements runs tier 2 content actions unit price Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Docker OPPO Reno Huawei Shulou Tech Info