Difference between staticmethod and classmethod

后端 未结 28 2195
一整个雨季
一整个雨季 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:34

    The definitive guide on how to use static, class or abstract methods in Python is one good link for this topic, and summary it as following.

    @staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.

    • Python does not have to instantiate a bound-method for object.
    • It eases the readability of the code, and it does not depend on the state of object itself;

    @classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance, can be overridden by subclass. That’s because the first argument for @classmethod function must always be cls (class).

    • Factory methods, that are used to create an instance for a class using for example some sort of pre-processing.
    • Static methods calling static methods: if you split a static methods in several static methods, you shouldn't hard-code the class name but use class methods

提交回复
热议问题