The difference between instance method, class method and static method usage in python

In Python, you can choose to use instance methods, class methods or static methods according to different needs.

1. Instance method (instance method):

        Instance methods should be used when accessing and manipulating instance attributes is required. The first parameter of an instance method is usually named self, which represents a reference to the current instance.

        Instance methods can access and modify instance attributes, and can also call other instance methods and class methods.

2. Class method (class method):

        Class methods should be used when you need to access and manipulate class attributes, or when you need to do some preparatory work before creating an object. Class methods are defined using the @classmethod decorator, and the first parameter is usually named cls, which represents a reference to the current class.

        Class methods can access and modify class attributes, and can also call other class methods.

3. Static method:

        Static methods should be used when implementing functionality that is related to a class but not to an instance. Static methods are defined using the @staticmethod decorator and require no additional parameters.

        Static methods can neither access instance properties and instance methods nor class properties and class methods.

4. Example code

        Although different types of methods can be selected according to the above rules, in actual use, sometimes it can also be selected according to personal preference and coding style.

How to use instance method, class method and static method specifically? According to the sample code below, you can understand!

Sample code 1:

class MyClass:
    class_variable = "Class Variable"

    def __init__(self, instance_variable):
        self.instance_variable = instance_variable

    def instance_method(self):
        print("Instance Method")
        print("Instance Variable:", self.instance_variable)
        print("Class Variable:", self.class_variable)

    @classmethod
    def class_method(cls):
        print("Class Method")
        print("Class Variable:", cls.class_variable)

    @staticmethod
    def static_method():
        print("Static Method")


# 使用实例方法:类初始化时必须传参数
obj = MyClass("Instance Variable")
obj.instance_method()

# 使用类方法
MyClass.class_method()

# 使用静态方法
MyClass.static_method()

        In the above sample code, a class named MyClass is first defined, which contains a class variable class_variable and an instance variable instance_variable, as well as three different types of methods: instance method instance_method, class method class_method and static method static_method.

        Then, an instance obj of MyClass is created, and the instance method instance_method is called, which can access and manipulate instance attributes and class attributes.

        At the same time, the class method class_method is called through the class name, which can access and manipulate class attributes.

        The static method static_method is also called through the class name, which has nothing to do with the class and instance, and cannot access class attributes and instance attributes.

        The above examples show how to use instance methods, class methods, and static methods, and select the corresponding method type to write code according to specific needs.

operation result:

Sample code 2:

class MyClass(object):

    def get_info(self, a, b):  # 定义实例方法,有 self 参数
        print("实例方法", a + b)

    @classmethod
    def get_other(cls, a, b):  # 定义实例方法,有 cls 参数
        print("类方法", a + b)

    @staticmethod
    def get_my_class(a, b):  # 定义静态方法,无默认参数
        print("静态方法", a + b)


class ExampleClass(object):
    def func(self):
        # 实例化

        # 调用实例方法
        MyClass().get_info(1, 6)  # 实例方法
        MyClass.get_info('', 1, 6)  # 实例方法

        # 调用类方法,建议通过 类对象.类方法([实参]) 方法调用
        MyClass.get_other(1, 6)  # 类方法
        MyClass().get_other(1, 6)  # 类方法

        # 调用静态方法,建议通过 类对象.类方法([实参]) 方法调用
        MyClass.get_my_class(1, 6)  # 静态方法
        MyClass().get_my_class(1, 6)  # 静态方法


if __name__ == '__main__':
    obj = ExampleClass()
    obj.func()

    print("*" * 100)

    obj2 = ExampleClass
    obj2.func(1)

operation result:

Sample code 3:  [Multi-thread execution]

from concurrent.futures import ThreadPoolExecutor


class BaseClass(object):
    pass


class MyClass(BaseClass):

    def get_info(self, a, b):  # 定义实例方法,有 self 参数
        print("实例方法", a + b)

    @classmethod
    def get_other(cls, a, b):  # 定义实例方法,有 cls 参数
        print("类方法", a + b)

    @staticmethod
    def get_my_class(a, b):  # 定义静态方法,无默认参数
        print("静态方法", a + b)


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=3) as executor:
        for i in range(5):
            executor.submit(MyClass.get_info, '', 1, 6)

    print("*" * 100)

    with ThreadPoolExecutor(max_workers=3) as executor:
        for i in range(5):
            executor.submit(MyClass().get_info, 1, 5)

operation result:

Guess you like

Origin blog.csdn.net/weixin_44799217/article/details/132093785