Difference between staticmethod and classmethod

后端 未结 28 2085
一整个雨季
一整个雨季 2020-11-21 06:11

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?

28条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 06:33

    Instance Method:

    + Can modify object instance state

    + Can modify class state

    Class Method:

    - Can't modify object instance state

    + Can modify class state

    Static Method:

    - Can't modify object instance state

    - Can't modify class state

    class MyClass:
        ''' 
        Instance method has a mandatory first attribute self which represent the instance itself. 
        Instance method must be called by a instantiated instance.
        '''
        def method(self):
            return 'instance method called', self
        
        '''
        Class method has a mandatory first attribute cls which represent the class itself. 
        Class method can be called by an instance or by the class directly. 
        Its most common using scenario is to define a factory method.
        '''
        @classmethod
        def class_method(cls):
            return 'class method called', cls
        
        '''
        Static method doesn’t have any attributes of instances or the class. 
        It also can be called by an instance or by the class directly. 
        Its most common using scenario is to define some helper or utility functions which are closely relative to the class.
        '''
        @staticmethod
        def static_method():
            return 'static method called'
    
    
    obj = MyClass()
    print(obj.method())
    print(obj.class_method()) # MyClass.class_method()
    print(obj.static_method()) # MyClass.static_method()
    

    output:

    ('instance method called', <__main__.MyClass object at 0x100fb3940>)
    ('class method called', )
    static method called
    

    The instance method we actually had access to the object instance , right so this was an instance off a my class object whereas with the class method we have access to the class itself. But not to any of the objects, because the class method doesn't really care about an object existing. However you can both call a class method and static method on an object instance. This is going to work it doesn't really make a difference, so again when you call static method here it's going to work and it's going to know which method you want to call.

    The Static methods are used to do some utility tasks, and class methods are used for factory methods. The factory methods can return class objects for different use cases.

    And finally, a short example for better understanding:

    class Student:
        def __init__(self, first_name, last_name):
            self.first_name = first_name
            self.last_name = last_name
    
        @classmethod
        def get_from_string(cls, name_string: str):
            first_name, last_name = name_string.split()
            if Student.validate_name(first_name) and Student.validate_name(last_name):
                return cls(first_name, last_name)
            else:
                print('Invalid Names')
    
        @staticmethod
        def validate_name(name):
            return len(name) <= 10
    
    
    stackoverflow_student = Student.get_from_string('Name Surname')
    print(stackoverflow_student.first_name) # Name
    print(stackoverflow_student.last_name) # Surname
    

提交回复
热议问题