Python - Difference between static method (staticmethod), class function (classmethod), member function

definition:

Static function (@staticmethod): that is, a static method, which mainly deals with the logical association with this class, such as verifying data;

Class function (@classmethod): that is, class method, which is more concerned with calling methods from classes, rather than calling methods in instances, such as constructing overloading;

Member function: the method of the instance, which can only be called through the instance;

 

class Foo(object):
    """Three grammatical forms of class methods"""

    def instance_method(self):
        print("It is an instance method of class {} and can only be called by instance objects".format(Foo))

    @staticmethod
    def static_method():
        print("It is a static method")

    @classmethod
    def class_method(cls):
        print("is a class method")

foo = Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print('----------------')
Foo.static_method()
Foo.class_method()

It can be seen from this, 

Instance methods can only be called by instance objects, static methods (methods decorated by @staticmethod), class methods (methods decorated by @classmethod), can be called by classes or instance objects of classes.
Instance method, the first parameter must pass the instance object by default.
Static method, parameters are not required.
Class method, the first parameter must be the default class.

 

how they are applied;

For example, the date method can output data by instantiating (__init__);

Data conversion can be done through class methods (@classmethod);

 

Data validation can be done through static methods (@staticmethod);

example

class Date(object):  
  
    day = 0  
    month = 0  
    year = 0  
  
    def __init__(self, day=0, month=0, year=0): //This is data output through an instance.
        self.day = day  
        self.month = month  
        self.year = year  
          
    def display(self):  
        return "{0}*{1}*{2}".format(self.day, self.month, self.year)  
     
    @classmethod  
    def from_string(cls, date_as_string): //Data conversion with class method
        day, month, year = map(int, date_as_string.split('-'))  
        date1 = cls(day, month, year)  
        return date1  
     
    @staticmethod  
    def is_date_valid(date_as_string): //At this time, the static method is used to verify the date data.
        day, month, year = map(int, date_as_string.split('-'))  
        return day <= 31 and month <= 12 and year <= 3999  
      
date1 = Date('12', '11', '2014')  
date2 = Date.from_string('11-13-2014')  
print(date1.display())  //12*11*2014
print(date2.display())  //11*13*2014  
print(date2.is_date_valid('11-13-2014'))  //False
print(Date.is_date_valid('11-13-2014'))  //False

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326545157&siteId=291194637