Class attributes, instance attributes and search order in Python (C3 algorithm)

Class attributes, instance attributes, search order in Python (mro search)

One, class attributes and instance attributes

Properties are some variables or methods defined in the class

Direct example

class A:
    name = 'A'
    def __init__(self):
        self.name = 'obj'

a = A()
print(a.name) # obj
class A:
    name = 'A'
    def __init__(self):
         pass

a = A()
print(a.name) # A

The order of attribute query is from bottom to top. When the above code is printed a.name, it will search in the instance first, and then go to the class attribute if it is not found.

Second, the search order when multiple inheritance (MRO algorithm)

From the python2.3beginning to the present python3, Pythonthe attribute search algorithms are collectively referred to as C3algorithms, a lot of formulas, Baidu.

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106911849