The difference between python instance methods, class methods and static methods

@ is the decorator in python

instance method

        Instance methods are functions defined directly in the class without any modification. Can only be called through an instantiated object of the class. Cannot be called by class name.

 class method

        Class methods are functions decorated with @classmethod in a class. Class methods need to have parameters representing class objects when they are defined (usually named cls, cls is a class object ). Class methods can be called through the instantiated object or the class name.

        Note: In Python, a class name is also an object without instance attributes and instance methods. The class object mentioned here is the class itself, not the instantiated object.

        Class methods are methods that belong to the entire class. Instance objects and methods cannot be called in class methods, but class methods, class objects and static methods can be called. The calling method must be called using a class object.

 static method

        A static method is a function in a class that can be modified with @staticmethod. No parameters are required in static methods, and class methods can be accessed through the instantiated object or class name.

        Static methods belong to the entire class and can only call static properties and static methods. Non-static properties and methods cannot be called (if you want to call, you must first create a new class object). Non-static methods can call both static properties and methods and non-static properties and methods.

        Note: When calling in a static function, you need to use the class name to call it. Class attributes are static attributes.

 

Guess you like

Origin blog.csdn.net/weixin_57023347/article/details/132528768