In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "Python decorator and class decorator", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Python decorator and class decorator how to achieve" article.
Decorator
What is a decorator? Although I feel strange to this time, there is no need to worry at all.
First of all, the decorator is also a function; it's just that the decorator can take a function and pass it as an argument.
And through return, you can return a function, the decorator receives a function, processes it, calls it inside the decorator, and returns a new function. At the same time, it can dynamically enhance the function of the incoming function.
The whole process of the decorator is as follows:
The A function is the decorator and the B function is the parameter passed in by the A function.
The B function is executed in the A function, and in the A function, you can choose to execute or not to execute, or you can reprocess the results of the B function.
Next, let's see what the decorator looks like.
Def a (): def b (): print (helloworld) b () a () b ()
A b () function is written in the a () function and the b () function is called in the a () function. Is it very similar to the example of defining a local function and calling it in a class? In fact, the decorator is something like this, except that the function called by the decorator is passed in as an argument and executed in the b () function.
We call the a () function after we have defined it, and we can handle it normally. But the b () function is a local function of the a () function that will report an error if it is called externally. (if the tenth line above, an error will be reported.)
Definition of decorator
Examples are as follows:
Def out (func_args): # the first layer function of the decorator is called the peripheral function, and the function defined by 'func_args' for the function to be processed def inter (* args, * * kwargs): # the function inside the peripheral function is called the embedded function The parameter passed in is the parameter of the func_args function to be processed # here we do not know what the parameter passed in by the func_args function is, so it is reasonable to write the variable parameter return func_args (* args, * * kwargs) # call the func_args function in the function body of the embedded function And pass in the variable parameter # actually we can deal with more logic here # We can choose to execute or not execute, or even reprocess the execution result of the func_args function. Return inter # after writing the business of the embedded function, we return the embedded function in the body of the peripheral function # it is important to note that It is not executed here (because there are no parentheses), which is the definition rule of the decorator and is essential # only if the peripheral function returns the embedded function, it can be executed by the later code (because all businesses are embedded in functions, the call cannot be performed without returning) the use of the decorator
In our daily work, decorators are used in two ways.
The first is to pass the called function directly into the outer function brackets of the decorator as a parameter. The example is as follows:
Def a (func): def b (* args, * * kwargs): return func (* args, * * kwargs) return bdef c (name): print (name) a (c) ('Neo') # > the execution result is as follows: # > Neo
The second kind: bind the decorator with the called function, the @ symbol + decorator function is placed on the top line of the called function, the called function is defined normally, and you only need to call the executed function directly. Examples are as follows:
Def a (func): def b (* args, * * kwargs): return func (* args, * * kwargs) return b@adef c (name): print (name) c ('Neo') # > the execution result is as follows: # > Neo
The most commonly used use of decorators is the second.
Now let's build a decorator that checks the string type to deepen our understanding of the decorator.
Def check_ok (func): def inner (* args, * * kwargs): result = func (* args * * kwargs) if result = = 'OK': return' the parameter data passed in is:\'% s\'% result else: return'. The parameter data passed in is not:\'OK\''return inner@check_okdef test_str (data): return dataresult = test_str (' OK') print (result) # > > the execution result is as follows: # > passed parameters The data is: 'OK'result = test_str (' NO') print (result) # > the execution result is as follows: # > the parameter data passed in is not: 'OK'
The above is a simple use of a decorator, follow-up learning content will be exposed to more advanced usage.
Decorator in class the decorator of the class-classmethod
Function of classmethod: class functions can be called directly without instantiation
The usage of classmethod: an example is as follows
@ classmethoddef func (cls,...): todo # > cls replaces self in ordinary class functions Change to cls to indicate that the current class # > self represents the instantiated object, so you can call # > cls to represent the class only after instantiation, so even if you do not instantiate You can also call # * * class Test (object): @ classmethod def add (cls, a, b): return a + bprint (Test.add (1,3)) # > the execution result is as follows: # > 4
Demo case:
Class Cat (object): def _ init__ (self, name): self.name = name def eat (self): print (self.name, 'like to eat fish') @ classmethod def work (cls): print ('can catch mice') dragonLi = Cat ('civet cats') print (dragonLi.eat (), dragonLi.work ()) # > > execution results are as follows: # > > civet cats like to eat fish # > can catch mice
Next, instead of instantiating the class, we directly use the class to call the eat () function and the work () function.
Class Cat (object): def _ _ init__ (self, name): self.name = name def eat (self): print (self.name 'like to eat fish') @ classmethod def work (cls): print ('can catch mice') dragonLi = Cat ('civet cat') Cat.eat () # > execution result is as follows: # > > TypeError: Cat.eat () missing 1 required positional argument: 'self'# > report missing important parameter' self' (no instantiated class) The class cannot call the class function directly) Cat.work () # > the execution result is as follows: # > > it catches the mouse # > the work () function bound to the classmethod decorator can be called directly by the class even if it is not instantiated.
Try again to see if the eat () function without a decorator and work () using the classmethod decorator can call each other.
Class Cat (object): def _ _ init__ (self, name): self.name = name def eat (self): print (self.name 'like eating fish') @ classmethod def work (cls): print ('can catch mice') cls.eat () # call the eat () function dragonLi = Cat ('civet cat') dragonLi.work () in the work () function of the classmethod decorator: # > TypeError: Cat.eat () missing 1 required positional argument: 'self' # > > same error missing important parameter 'self'class Cat (object): def _ _ init__ (self) Name): self.name = name def eat (self): print (self.name, 'like fish') self.work () @ classmethod def work (cls): print ('catching mice') dragonLi01 = Cat ('civet cats') dragonLi01.eat () # > execution results are as follows: # > civet cats like to eat fish # > can catch mice
Combining the above two scenarios, we come to the following conclusions:
A normal function with self cannot be called within a function with a classmethod decorator
But in ordinary class functions with self, functions with classmethod decorators can be called.
Class decorator-staticmethod
The function of staticmethod: the class function can be called directly without instantiation. The function called by the decorator does not need to pass self and cls parameters, and other class functions or class variables cannot be called within this function.
Usage of staticmethod: refer to the following
@ staticmethoddef func (...): todo # > No cls or self parameters are required in the function # * class Test (object): @ staticmethoddef add (a, b): return a + bprint (Test.add (1) 3)) # > the execution result is as follows: # > 4
Next, let's demonstrate the staticmethod decorator on the basis of the Cat () class above (create a new color () function, using the staticmethod decorator)
Class Cat (object): def _ init__ (self, name): self.name = name def eat (self): print (self.name, 'like fish') self.work () @ classmethod def work (cls): print ('can catch mice') @ staticmethod def color (): print ('yellowish brown') dragonLi = Cat ('civet cat') print (dragonLi.eat () DragonLi.color () # > execution results are as follows: # > civet cats like to eat fish # > > can catch mice # > yellowish brown # > > judging from the execution results The color () function of the staticmethod decorator can be called by the instantiated object dragonLi. # > can it be called directly by the Cat () class? Let's look down at print (Cat.color ()) # > the execution result is as follows: # > yellowish brown # > > you can see that the color () function constructed by the staticmethod decorator can still be called directly by the class even if it is not instantiated.
Similarly, try whether the color () function constructed by the staticmethod decorator can call each other in class functions.
Class Cat (object): def _ _ init__ (self, name): self.name = name def eat (self): print (self.name Self.work () self.color () @ classmethod def work (cls): print ('catching mice') @ staticmethod def color (): print ('yellowish brown') dragonLi = Cat ('civet cat') dragonLi.eat () # > the execution results are as follows: # > civet cats like to eat fish # > can catch mice # > yellowish brown Combined with the execution results, it is concluded that the color () function constructed by the staticmethod decorator can be called in the eat () function.
Like functions with classmethod decorators, functions constructed by staticmethod decorators cannot call ordinary functions with self, so no demonstration code will be written here. (functions constructed by the staticmethod decorator cannot also be called. Ordinary functions with self will report an error: NameError: name 'self' is not defined)
Class decorator-property
The function of property: you can remove parentheses from the execution of class functions, similar to calling variables (attributes) of the class directly.
Usage of staticmethod: refer to the following
@ propertydef func (self): todo # > parameters cannot be passed in No important function description # * example is as follows * class Test (object): def _ _ init__ (self) Name): self.name = name @ property def call_name (self): return 'Hello {}' .format (self.name) test = Test ('Neo') result = test.call_name # you can call the call_name function without adding parentheses # with regard to the non-transferable parameters of staticmethod, it is not that parameters cannot be passed, but that the passed methods are more alternative. Let's move on to print (result) # > the execution result is as follows: # > Hello Neo
Recreate a Dog class, and then we'll move on to the demonstration.
Class Dog (object): def _ init__ (self, name): self.__name = name @ property def type (self): if self.__name in ['husky', 'Samoye', 'Arasky']: return self.__name,'is a sled dog Elif self.__name in [Chihuahua, Pomeranian, Yorkshire]: return self.__name, else: return self.__name, I don't know what kind of dog this is. Maybe it's a relative of 'dog = Dog (name=' husky') print (dog.type) # here we don't need dog.type + () parentheses to call the type () function # > the result is as follows: # > ('husky', "it's a sled dog, one of the three idiots of the sleigh') # > > here we see that when the Dog class instantiates the dog variable The 'husky' parameter we pass in is immutable. What if we try to modify the passed parameter by assignment? Dog = Dog (name=' husky') dog.type = 'Yorkshire' print (dog.type) # > the execution result is as follows: # > AttributeError: can't set attribute# > error: property error, you can't set this property # > in fact, the parameter of the function bound by property decorator is not unchangeable, but the way to change it is special, it's not that you can't pass in parameters in the form of assignment, so let's move on.
First, we have bound our type function with @ property, which is a method that returns a value. So how do we assign a value to the type () function? In fact, it is very simple, we can use @ type to correspond to the type () function, and there is a function setter inside its function; then we define a type function that defines a value value in this newly defined type () function (it can be any name, but it should be noted here that only one value can be defined). Then you can modify the incoming parameters by setting a self.__name = value. To cut the crap, look at the example below:
Class Dog (object): def _ init__ (self, name): self.__name = name @ property def type (self): if self.__name in ['husky', 'Samoye', 'Arasky']: return self.__name,'is a sled dog Elif self.__name in [Chihuahua, Pomeranian, Yorkshire]: return self.__name, else: return self.__name, I don't know what kind of dog this is. Maybe it is a relative of\ 'Tai Ritian\' @ type.setter def type (self, value): self.__name = valuedog = Dog (name=' husky') dog.type = 'Yorkshire' print (dog.type) # > the execution result is as follows: # > (Yorkshire, 'small dog')
Attachment: the most widely used decorator is classmethod
The above is about "Python decorator and class decorator how to achieve" the content of this article, I believe we all have a certain understanding, I hope the editor to share the content to help you, if you want to know more related knowledge, please pay attention to the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.