Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python function decorator

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to use the Python function decorator, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Definition of decorator

With regard to the definition of decorator, let's first take a look at the definition of a big guy on github:

Function decorators are simply wrappers to existing functions.

In the context of design patterns,decorators dynamically alter the functionality of a function, method or class without having to directly use subclasses.

This is ideal when you need to extend the functionality of functions that you don't want to modify.

We can implement the decorator pattern anywhere, but Python facilitates the implementation by providing much more expressive features and syntax for that.

The main meaning of this passage is:

Function decorators are simple containers for existing functions.

In the original code environment, it can dynamically change the function of a function, or change methods and classes without directly using subclasses.

This is a good idea when you don't want to modify the source code but want to expand the functionality.

We can use the decorator style in any case, and Python helps with the decorator by providing more powerful properties and syntax.

The meaning of decorator

In fact, we already know the meaning of the decorator in the above.

We can directly expand the function without modifying the source code, but we need to pay more writing time to do so.

And more importantly, the addition of functionality by modifying the source code often changes the parameters passed by the interface, but there are often many interfaces in a project, which means that you may need to change the interface parameters many times.

We don't do this workload!

Use of decorator No-parameter decorator

No-parameter decorator is the most basic decorator.

The fundamental reason is that the decorated function object does not need parameters that are still and.

Let's demonstrate how the simplest decorator is implemented:

Def greeting (): # define a basic no-parameter function return "Hello, readers!" # now what I need to do is to make the output content become

"Hello, readers."

# without directly changing the greeting function, we need to use the no-parameter decorator def decorator_p (func): # to receive a function def wrapper (): return f'

{func ()}

'return wrapperdecorator = decorator_p (greeting) # calls decorator_p and receives the return value print (decorator ()) with a decorator

Hello, readers!

The above is the result of the output

But I am not satisfied with the result.

Because after completing the function attachment, we still need to use decorator = decorator_p (greeting) to receive it, and in this way, the calling method is no longer the original greeting (), but decorator ().

Both of these already provide solutions for Python, which pursues efficiency and elegance.

Let me explain:

# for the calling mode, the first solution we can think of is greeting = decorator_p (greeting) # pass the original greeting function to decorator_p, and rename print (greeting ()) # the output is the same as the original, but this can still be improved, using @ provided by Python But when using this method, you must pay attention to the order of writing, so the code must be changed like this: def decorator_p (func): def wrapper (): return f'

{func ()}

The return wrapper@decorator_p # effect is equivalent to greeting = decorator_p (greeting) def greeting (): return "Hello, readers!" print (greeting ())

Hello, readers!

The result is what we want, but the order of using this method is particularly important.

If you write in this way, an error will be given:

@ decorator_p # after using this @, you will start looking up for the decorator_p function def greeting (): return "Hello, readers!" print (greeting ()) def decorator_p (func): def wrapper (): return f'

{func ()}

'return wrapper

NameError: name 'decorator_p' is not defined

The reason for the error given is that the function decorator_p was not found.

But it is clear that we have completed the definition of this function

So the conclusion we can get is:

When you use @, you start looking up for a function, and when you can't find it, you get an error.

Parameter decorator

Next, we will introduce the parameter decorator, which refers to the decorator that needs to pass parameters.

In fact, the use of non-parameter decorators has been introduced above, and it is not very difficult to have parameter decorators.

Here's a demonstration:

Def decorator (func): def wrapper (name): return f'

{func (name)}

'return wrapper@decoratordef greeting (name): return f "Hello, {name}!" print (greeting (' Reader')) # pass a parameter

Hello, Reader!

Practice by example

OK, after the introduction above, all readers should be in a state of incomprehension again.

So adhering to the concept of one article and one practice, we will next take a closer look at the difference between using decorators and not applying decorators by writing login functions.

Before I begin, I have created a text folder that will be used to simulate the information stored by the user, as follows:

Sign_in.txtJoseph:JostarJonasen:JostarKujo:JotaroJolin:KujoDiavollo:Doppio

List of requirements:

1) user accounts can only be composed of numbers and English, with a length of no more than 16 characters

2) the user password can only be composed of numbers and English, with a length of no more than 16 characters

3) the user has 4 input opportunities.

# No function # No decorator login function count = 1 # used to calculate the number of uses while count < 5: user_account = input ('Please enter your account') if user_account.isalnum () and len (user_account) length: print ('account name or password length does not conform to the specification') check = False Return check return checkdef limit_composition (name Keyword):''used to determine whether the composition of the user's name and password meets the standard: param name: used to accept the user's name: param keyword: used to accept the user's password: return: check: used to determine whether the input meets the length standard For more information, please see''check = True if name.isalnum () is not True or keyword.isalnum () is not True: print (' account name or password composition does not conform to the specification') check = False return check return checkdef verify_useinfo (name) in the decorator Keyword):''used to verify whether the account and password entered by the user are in accordance with the file: param name: used to accept the user's name: param keyword: used to accept the user's password: return: check: used to determine whether the input meets the length standard For more information, please see''check = True with open (' sign_in.txt','r') as file: for line in file: r_name, r_keyword = line.strip () .split (':') if r_name = = name and r_keyword = = keyword: print ('login successful) in the decorator. Welcome to') return check else: check = False print ('wrong account password Please re-enter') return check@passing_func (limit_len, limit_composition, verify_useinfo) def input_signup (): user_name = input ('Please enter your account name') user_keyword = input ('Please enter your account password') return user_name. This is the answer to user_keyword 's question on how to use the Python function decorator. I hope the above can be helpful to you. If you still have a lot of questions to solve, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report