理解@staticmethod||@classmethod||instancemethod in Python

    技术2024-07-12  73

    staticmethod()

    The staticmethod() built-in function returns a static method for a given function.

    The syntax of staticmethod() is :

    staticmethod(function)

    Using staticmethod() is considered a un-Pythonic way of creating a static function.

    Hence, in newer versions of Python, you can use the @staticmethod decorator.

    The syntax of @staticmethod is :

    @staticmethod def func(args, ...)

    staticmethod() Parameters

    The staticmethod() method takes a single parameter:

    function - function that needs to be converted to a static method
    Return value from staticmethod()

    The staticmethod() returns a static method for a function passed as the parameter.

    So, what is the static method?

    Static methods, much like class methods, are methods that are bound to a class rather than its object.

    They do not require a class instance creation. So, they are not dependent on the state of the object.

    What is the class methods?

    The classmethod() method returns a class method for the given function.

    The syntax of a classmethod() method is :

    classmethod(function)

    or more Pythonic :

    @classmethod def func(cls, args, ...)

    the classmethod() returns a class method for the given function.

    A class method is a method that is bound to a class rather its object.

    It doesn’t require creation of a class instance, much like staticmethod.

    No matter what , the class method is always attached to a class with first argument as the class itself cls.

    When do you use class method?

    Factory methods

    Factory methods are those methods which return a class object( like constructor) for different use cases.

    Correct instance creation in inheritance

    Difference between a static method and a class method

    Static method knows nothing about the class and just deals with the parametersClass method works with the class since its parameter is always the class itself

    They can be called both by the class and its object.

    Class.staticmethodFunc() or even Class().staticmethodFunc()

    Much more information refer to : Difference between staticmethod and classmethod

    When do you use static methods

    Grouping utility function to a class

    When you need a utility function that doesn’t access any properties of a class but makes sense that it belongs to the class, we use static functions.

    A static method doesn’t need to access any properties of the class.

    Having a single implementation

    Static methods are used when we don’t want subclasses of a class change/override a specific implementation of a method.

    References

    菜鸟教程正确理解Python中的 @staticmethod@classmethod方法Programiz : Python staticmethod()Difference between staticmethod and classmethodReal Python : Python’s Instance, Class, and Static Methods Demystified
    Processed: 0.033, SQL: 9