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

The method course of Python decorator for beginners

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "suitable for beginners Python decorator method tutorial", in the daily operation, I believe that many people have doubts in the method tutorial of Python decorator for beginners, Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the "method tutorial for beginners Python decorator". Next, please follow the editor to study!

Decorators are a fairly advanced part of the Python programming language. Like most things, once you have mastered how they work and use them a few times, they become very simple and straightforward, but as a beginner, they can be a little daunting and difficult to understand. Only by understanding the problem it solves can you really understand it. For example, I can directly declare the definition of the decorator:

Decorator is a function that takes another function as an argument and returns a modified version of it, enhancing its functionality in some way.

If you already know what decorator is, the definition is clear, but if you don't, you probably don't. Importantly, this definition alone doesn't tell you when to use modifiers, or how bad it would be without a modifier Python.

Give an example

We'll start with a hypothetical scenario and look at the problems that may arise if you don't use decorator. On your first day at work, your boss comes to you and asks you to write a function that converts a string into a palindrome: a string that reads the same content forward and backward.

You can write like this:

Def make_palindrome (string): "Makes a palindromic mirror of a string." Return string + string [::-1]

So far so good. An hour later, the boss asked for more functions: a credits function to add a string to the end of any string, a function to convert a string to another string, and a function to insert a comma into a string.

You start adding new functions:

Def add_credits (string): "Adds the company's credits to the end of any string." Return f "{string} (string created by Pro String Inc.)" Def snake_to_camel (string): "Converts a string in snake_case to camelCase." Words = string.split ("_") if len (words) > 1: words = [words [0]] + [word.title () for word in words [1:]] return ".join (words) def insert_commas (string, spacing=3):" Inserts commas between every n characters. "" Sections = [string [I: I + spacing] for i in range (0, len (string), spacing)] return "," .join (sections)

But there's a problem. The boss looks at your code and reminds you that functions must be able to accept integers as input and that they should be converted to strings. He suggests adding a line at the beginning of each function to check whether the input is an integer and convert if it is an integer.

This will demoralize you-you have to check every feature, and then add something like this at the beginning:

If isinstance (string, int): strstring = str (string)

This is fine when we have four functions that need to be modified, but what if we have ten? Letting all functions start with the same two lines violates the sacred legal principle of "Don't repeat yourself".

Isn't there a way to just modify all these functions without adding extra code? To understand how to do this, let's go back to the Python function. Although the Python function has a special syntax, it is just an object, just like a string or list. You can check their properties, assign them to new variables, and-- crucially-- pass them as arguments to another function.

For example, you can make one function accept another function and check whether it has any keyword arguments:

Def func_has_kwargs (func): return len (func.__defaults__) > 0

Don't worry about _ _ defaults__ if you haven't seen it yet, the key here is that the function is another function as an argument, check if there are any keyword arguments (that is, if the length of the _ _ default__ property is greater than 0), otherwise, return True, if so, return False.

Now let's get back to our problem. We have three well-designed string manipulation functions that we need to modify so that they also accept integers. What we need is a new function-- it will take our existing function as input and create a modified function to check integers. We need a decorating function:

Let's take a closer look at what's going on here. Accept_integers is our decorating function-- it takes one function as input and returns another function as output. In its body, it creates a new function that should do everything the input function does, but requires an extra step at the beginning. If you look at the body of this function, you can see that it checks whether the given string is an integer, converts it if it is an integer, and then passes the string to the original function. There is a missing step-- we need to actually use this decorator:

Standard form

Finally, it is worth pointing out that although the above syntax is completely valid, Python provides shortcuts in the form of the @ symbol. You can decorate it by adding @ accept_integers in front of any function:

This is another way to pass one function to another. At the bottom, when Python sees the @ symbol, it makes a call to decorator for you. Many Python libraries provide decorators to quickly enhance written functions without having to enter a lot of repetitive code.

At this point, on the "suitable for beginners of the Python decorator method tutorial" is over, I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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