Python's @classmethod and @staticmethod

Source: Internet
Author: User
Tags date1 instance method

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:

    1. Class Date(object):
    2. def __init__(self, day=0, month=0, year=0):
    3. Self.day = Day
    4. Self.month = Month
    5. 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:

    1. Day, month, year = map (int, string_date.split ('-'))
    2. 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:

    1. @classmethod
    2. def from_string(CLS, date_as_string):
    3. Day, month, year = map (int, date_as_string.split ('-'))
    4. Date1 = CLS (Day, month, year)
    5. Return date1
    6. 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:

    1. @staticmethod
    2. def is_date_valid(date_as_string):
    3. Day, month, year = map (int, date_as_string.split ('-'))
    4. Return day <= and month <= <= 3999
    5. # Usage:
    6. 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()
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

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 ()         
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

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 ()   
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

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 ( ) 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

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 ()
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

Error:
Method cannot be called normally. If you want to call, the following:

cat.intro
    • 1

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            
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

Cat.intro There are other operations getter Deleter and so on.

Python's @classmethod and @staticmethod

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.