This article is a stackoverflow on the GAO Zan answer to the incomplete translation, the original link: meaning-of-classmethod-and-staticmethod-for-beginner
In Python object-oriented programming, a method defined in a class can be a class method of @classmethod decoration, or a static method of @staticmethod decoration, with the most or an instance method without an adorner. For convenience, in the following @classmethod decorate the class method will be directly used @classmethod to express, @staticmethod the same, hope readers in reading to distinguish themselves.
@classmethod and @staticmethod are very similar, the way they decorate is only a little different in use: The method of @classmethod decoration The first argument must be a class (usually a CLS). The method of @staticmethod decoration is to set parameters according to business requirements, or no parameters at all.
Sample Example
The sample is a class that processes date information, as follows:
- Class Date(object):
- def __init__(self, day=0, month=0, year=0):
- Self.day = Day
- Self.month = Month
- Self.year = Year
This class can be used to store a specified date (excluding time zone information, assuming all dates are UTC time).
This class has a __init__ function that initializes the instance object, and its first required argument, self, points to an instance object of the created Date class, which is a typical instance method.
Class Method
Some tasks can be done well with @classmethod.
Let's say we're going to create many instances of the corresponding date class from a bunch of strings that have a certain number of dates, such as ' dd-mm-yyyy ', and that's going to happen everywhere in the project. So what we're going to do is:
1. Parse a string to get the three integer variables of day,month,year or assemble a tuple
2. Pass these values to the initialization function to instantiate the date instance object
Like what:
- Day, month, year = map (int, string_date.split ('-'))
- Date1 = Date (day, month, year)
For this purpose, C + + can use overloads, but Python does not have such syntax, but it can be implemented using @classmethod, as follows:
- @classmethod
- def from_string(CLS, date_as_string):
- Day, month, year = map (int, date_as_string.split ('-'))
- Date1 = CLS (Day, month, year)
- Return date1
- Date2 = date.from_string (' 11-09-2012 ')
Comparing these two methods carefully, using @classmethod has the following advantages:
1. We have only written a method for converting strings, and this method is reusable.
2. Wrap this method in a class, more tightly (you might think that you can write a separate function to convert the string, but use @classmethod to be more consistent with object-oriented thinking).
3. The CLS is the object of the class itself, not the instance object of the class, so that objects that inherit from date will have the From_string method.
Static Method
What about @staticmethod? In fact, it is very similar to @classmethod, except that it does not have any necessary parameters.
Suppose we're going to check if a date's string is valid. This task is related to the date class, but does not require a date instance object, in which case the @staticmethod can come in handy. As follows:
- @staticmethod
- def is_date_valid(date_as_string):
- Day, month, year = map (int, date_as_string.split ('-'))
- Return day <= and month <= <= 3999
- # Usage:
- Is_date = Date.is_date_valid (' 11-09-2012 ')
As you can see from the above usage, it is just a function that invokes the same syntax as the normal method call, and does not access the instance object and its internal fields and methods.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Here are the wrong places
Common methods of Class
class Animal(object): def __init__(self,name): self.name = name def intro(self): print(‘there is a %s‘%(self.name))cat = Animal(‘cat‘)cat.intro()
Static class methods
class animal (object): def __init__ Self, Name): Self.name = name @staticmethod def intro (self): print ( There is a%s '% (self.name)) Cat = Animal ( ' cat ') Cat.intro ()
Adding an adorner will result in an error, because the method becomes a normal function, detached from the relationship to the class, and cannot reference the variables in the constructor.
Examples of using scenarios: Python's methods in the built-in method OS, which can be used directly by the toolkit, do not matter with the class.
class animal (object): def __init__ Self, Name): Self.name = name @classmethod def intro (self): print ( There is a%s '% (self.name)) cat = Animal ( ' cat ') Cat.intro ()
Error message
If you replace
class animal (object): Name = ' cat ' def __init__< Span class= "Hljs-params" > (self,name): self.name = name @classmethod def intro (self): Print ( There is a%s '% (self.name)) cat = Animal ( ' cat ') Cat.intro ( )
can run correctly.
Conclusion: Class methods can only call class variables and cannot invoke instance variables
The @property property method turns a method into a (disguised) class property. Because the nature of a class property is a class variable, the user can modify the variable by invoking the variable. Static methods are used to restrict user behavior for certain scenarios.
@property is widely used in the definition of a class, allowing the caller to write short code while guaranteeing the necessary checks on the parameters, thus reducing the likelihood of errors when the program runs. (from Liaoche's blog)
class animal (object): def __init__ Self, Name): Self.name = name @property def intro (Self,food): Print ( ' There is a%s eating%s '% (Self.name,food)) cat = Animal ( ' cat ') Cat.intro ()
Error:
Method cannot be called normally. If you want to call, the following:
cat.intro
However, there is no way to pass in the parameters individually. If you want to pass in a parameter, as follows:
class animal def __init__ (self,name): self.name = name @property def Intro ' There is a%s eating%s '% (Self.name,food)) Span class= "Hljs-decorator" > @intro. Setter def intro (Self,food): passcat = Animal ( ' cat ') Cat.intro
Cat.intro There are other operations getter Deleter and so on.
Python's @classmethod and @staticmethod