Python built-in property, Staticmethod, Classmethod three adorners, sometimes we also use, here is a simple explanation
1. Property
Function: As the name implies, decorate functions as attributes
In general, we call class method members, which are written as follows:
Class PropertyTest (): def __init__ (self,x,y): self.x = x self.y = y def square (self): return self.x * Self.ypt = propertytest (3,5) print (Pt.square ())
Here's a look at square as a method of the class, but if it is written in the following form, then it is not certain that the invocation must be a class method:
Class PropertyTest (): def __init__ (self,x,y): self.x = x self.y = y @property def square (self): return self.x * self.ypt = propertytest (3,5) print (Pt.square)
The calling method here is similar to calling a member variable, and if written as print (Pt.square ()) the compiler will error
This is the use of the property, to change a method into a variable to invoke
2, Staticmethod
Function: The method in the class can be called directly without instantiation, as shown below
Class A (): def __init__ (self): pass @staticmethod def plus (x, y): print (x*y) c = A () c.plus (2,3) A.plus (4,5)
We can instantiate class A and then call the method plus or directly class. Method call
3, Classmethod
Function: Similar to Staticmethod, the difference is that the calling class is passed in as the first parameter, as follows:
Class A (): def __init__ (self): pass @classmethod def Plus (cls,x,y): print (CLS) print (x*y ) A.plus (4,5) c = A () c.plus (5,6)
Here print (CLS) prints Class A, other usages are the same as Staticmethod
Python interior decorator (property/staticmethod/classmethod)