Python advanced syntax_instance method, static method, class method

Python advanced syntax

Instance method, static method, class method

Class attribute, instance attribute

They are different in definition and use, and the most essential difference is the different locations stored in the memory.

  • Instance attributes belong to objects
  • Class attribute belongs to class

Code example:

class Province(object):
    # 类属性
    country = '中国'

    def __init__(self, name):
        # 实例属性
        self.name = name


# 创建一个实例对象
obj = Province('山东省')
# 直接访问实例属性
print(obj.name)
# 直接访问类属性
Province.country

From the above code, it can be seen that [instance attributes need to be accessed through objects] [class attributes are accessed through classes]. In use, it can be seen that the attributes of instance attributes and class attributes are different.

The storage method in the content is similar to the following figure:

Class attribute, instance attribute

It can be seen from the figure above:

Only one copy of class attributes is stored in memory, and one copy of
instance attributes is stored in each object.

Application scenarios:

When creating an instance object through a class, if each object needs an attribute with the same name, then use the class attribute and use one copy.

Instance method, static method and class method

Methods include: instance methods, static methods and class methods,The three methods belong to the class in memory, the difference lies in the different calling methods.

  • Instance method: called by the object; at least one self parameter; when the instance method is executed, the object calling the method is automatically assigned to self;
  • Class method: called by the class; at least one cls parameter; when the class method is executed, the class that calls the method is automatically assigned to cls;
  • Static method: called by the class; no default parameters;

Code example:

class Foo(object):
    def __init__(self, name):
        self.name = name

    def ord_func(self):
        """ 定义实例方法,至少有一个self参数 """
        # print(self.name)
        print('实例方法')

    @classmethod
    def class_func(cls):
        """ 定义类方法,至少有一个cls参数 """
        print('类方法')

    @staticmethod
    def static_func():
        """ 定义静态方法 ,无默认参数"""
        print('静态方法')



f = Foo("中国")
# 调用实例方法
f.ord_func()

# 调用类方法
Foo.class_func()

# 调用静态方法
Foo.static_func()

Class method, instance method, static method

Compared:

  • Similarity: For all methods, they belong to the class, so only one copy is saved in memory
  • Differences: The method caller is different, and the parameters automatically passed in when the method is called are different.

Guess you like

Origin blog.csdn.net/weixin_42250835/article/details/89943985