Python - Object-oriented attribute, class method, static method, instance method difference and detailed usage

I. Introduction

  • In Python's object-oriented programming, class attributes and instance attributes are two different concepts, and they differ in scope and usage.
  • There are three methods in object-oriented programming in Python: instance methods, class methods and static methods. The differences between them are mainly reflected in the way parameters are passed and called.

2. Object-oriented - class attributes and instance attributes

1. Difference

In Python, the difference between class attributes and instance attributes is their different scopes.

  • A class attribute is an attribute that belongs to a class object, and its value is the same for all instances of the class. A class attribute can be accessed by the class name or the instance name .
  • Instance attributes are attributes that belong to instance objects, and each instance can have its own attribute values. Instance properties can only be accessed through the instance name .

2. Sample code

class MyClass:
    class_attr = "I am a class attribute"

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


if __name__ == '__main__':
    obj1 = MyClass("I am an instance attribute of obj1")
    obj2 = MyClass("I am an instance attribute of obj2")

    print(obj1.class_attr)  # 输出 "I am a class attribute"
    print(obj2.class_attr)  # 输出 "I am a class attribute"

    print(obj1.ins_attr)  # 输出 "I am an instance attribute of obj1"
    print(obj2.ins_attr)  # 输出 "I am an instance attribute of obj2"

    obj1.class_attr = "I am a new update class attribute of obj1"
    print(obj1.class_attr)  # 输出 "I am a new update class attribute of obj1"
    print(obj2.class_attr)  # 输出 "I am a class attribute"

    MyClass.class_attr = "I am a new MyClass attribute"
    print(obj1.class_attr)  # 输出 "I am a new update class attribute of obj1"
    print(obj2.class_attr)  # 输出 "I am a new MyClass attribute"
    print(MyClass.class_attr)  # 输出 "I am a new MyClass attribute"

In the above code, we defined a MyClass class, which has a class attribute class_attr and an instance attribute name. After instantiating obj1 and obj2, we accessed their instance attributes and class attributes respectively, then we modified the value of the class attribute, and accessed the class attribute values ​​of the two instances respectively, and finally printed the attribute value of each instance. .

The running results are as follows

Insert image description here
As can be seen from the above running results,

  • When we 实例对象modify according to usage 类属性, the class attributes of the instance object will change, but it will only affect itself (the modified instance object) and will not affect the attribute values ​​of other instances.
  • When we modify it directly 类属性, the class attributes will change and take effect on other instance objects. The access results of other instance objects will become the results of the modified class attributes of the class, while the modified class attributes of the instance object are not affected. Impact , the value of its class attribute is its (instance object) modified value.

3. Summary

  • Class attributes are global variables of a class. All instance objects share a value that can be accessed through the class name or instance object. In addition, it should be noted that different modification methods may affect the final output result of the class attributes.
  • Instance properties are private properties of instance objects. Each instance object has its own value and can only be accessed through the instance object.

In actual development, it is necessary to choose the use of class attributes and instance attributes according to the actual situation.

2. Commonly used class attributes, method decoration methods and usage

1. @property

Convert a method into a property that can be accessed like a property.

class MyClass:
    def __init__(self, value):
        self._x = value
    
    @property
    def x(self):
        return self._x
    
c = MyClass(5)
print(c.x)  # 输出5

2. @classmethod

Declare a method as a class method and call it with the class name.

class MyClass:
    x = 0
    
    @classmethod
    def classmethod(cls):
        cls.x += 1
        return cls.x
    
print(MyClass.classmethod())  # 输出1
print(MyClass.classmethod())  # 输出2

3. @staticmethod

Declaring a method as a static method can be called without instantiating the object.

class MyClass:
    @staticmethod
    def staticmethod():
        return "This is a static method."
    
print(MyClass.staticmethod())  # 输出"This is a static method."

4. @get.setter

The method used to set the property value must be defined under the @property method.

class MyClass:
    def __init__(self, value):
        self._x = value
    
    @property
    def x(self):
        return self._x
    
    @x.setter
    def x(self, value):
        self._x = value * 2
    
c = MyClass(5)
print(c.x)  # 输出5
c.x = 10
print(c.x)  # 输出20

5. @get.deleter

The method used to delete attributes must be defined below the @property method.

class MyClass:
    def __init__(self, value):
        self._x = value
    
    @property
    def x(self):
        return self._x
    
    @x.deleter
    def x(self):
        del self._x
    
c = MyClass(5)
print(c.x)  # 输出5
del c.x
# print(c.x)  # AttributeError: 'MyClass' object has no attribute '_x'

6. @cached_property

Cache attributes are only calculated once, and subsequent accesses directly return the cached value.

from cached_property import cached_property

class MyClass:
    @cached_property
    def x(self):
        print("Calculating x.")
        return 5
    
c = MyClass()
print(c.x)  # 输出Calculating x. 5
print(c.x)  # 输出5

7.@lazy_attribute

The calculation is performed on the first access to the property, and the cached value is returned thereafter.

from lazy_object_proxy import Proxy

class MyClass:
    def __init__(self):
        self._my_property = Proxy(self.calculate_my_property)

    def calculate_my_property(self):
        print("Calculating my_property!")
        return 100

    @property
    def my_property(self):
        return self._my_property

my_class = MyClass()
print(my_class.my_property) # Output: Calculating my_property! 100
print(my_class.my_property) # Output: 100

2. Object-oriented - class methods, static methods, instance methods

1. The main differences between the three:

1. Class method:

Use @classmethoda decorator for decoration. The first parameter defaults to cls, representing the class itself. Class methods can be called by classes and instance objects of the class. Instance properties and instance methods cannot be accessed in class methods because it does not rely on any instance object, but relies on the class itself. It is usually used to create class objects or operate on class properties.

2. Instance methods:

Instance methods do not have any special decorators, and the first parameter defaults to self, representing the instance itself. An instance method can only be called by an instance object because it depends on the instance object. Instance methods can access the properties and other instance methods of the instance object.

3. Static method:

Use @staticmethoda decorator for decoration, it does not need to represent its own object selfand clsparameters. A static method is a toolkit of a class, which has nothing to do with the class and instance objects, and is usually used for tool functions or class initialization operations.

2. Also introduce the difference between class methods and instance methods:

  • Class methods are @classmethoddecorated with decorators, while instance methods are not.
  • The first parameter of a class method is the class object ( cls), while the first parameter of an instance method is the instance object ( self).
  • Class methods can be called directly through the class name, while instance methods must be called through the instance object.
  • Class methods are the same for all instances, while instance methods may be different for each instance.
  • Class methods are usually used to create, modify, and query class attributes and class status, while instance methods are usually used to operate instance attributes and instance status.
  • Class methods can access class attributes, but not instance attributes. Instance methods can access instance attributes and class attributes.

When using class methods and instance methods, you need to choose which method to use based on specific business needs.

3. Sample code description and explanation

1. Instance method:

In Python, all functions in a class are instance methods by default. An instance method is a selfmethod that takes as the first parameter. It can be called by instantiating an object. It can access the data in the instance and can also modify the instance. data, one of the most commonly used methods.

class MyClass:
    def my_instance_method(self, arg1, arg2):
        # 实例方法的代码
        pass

instance = MyClass()
instance.my_instance_method(arg1, arg2)

2. Class methods:

A class method is a method that takes cls as the first parameter. It can be called through the class name or object name@classmethod , and it can also modify class variables. However, it cannot access instance variables. Class methods are defined using decorators.

Sample code

class MyClass:
    class_var = 0

    @classmethod
    def my_class_method(cls, arg1, arg2):
        # 类方法的代码
        cls.class_var += 1
        pass

MyClass.my_class_method(arg1, arg2)

3. Static method:

Such methods are also class member methods, but they do not require access to the class or instance context. Static methods can be called like ordinary functions, without default parameters.
Static methods do not need to pass any parameters. They have nothing to do with classes and instances. They can be called using class names or object names. Therefore, static methods cannot access instance variables or class variables. Static methods are defined using decorators @staticmethod.

class MyClass:
    @staticmethod
    def my_static_method(arg1, arg2):
        # 静态方法的代码
        pass

MyClass.my_static_method(arg1, arg2)

3. Summary:

  • Instance methods are the most commonly used method types and can only be called by instances. The first parameter is self;
  • Both class methods and static methods are class member methods, which can be called through the class or instance;
  • The first parameter of the class method is cls, indicating the current class object;
  • Static methods have no default parameters and the context of the class is not passed to it.

The above is a detailed explanation of the differences and usage of object-oriented attributes, class methods, static methods, and instance methods in python. I hope it will be helpful to you. Please feel free to give me your help. Thank you!

Guess you like

Origin blog.csdn.net/qq_43030934/article/details/132459157