SoFunction
Updated on 2024-11-16

Class mro and inheritance relationships in Python in detail

preamble

Version:

  • windows 10.0
  • python 3.8

resemble

existPython Number Comparison and Class StructureThere is a brief mention of classes, so what is a class?

Defining a class in python is simple, using the keywordclassIt will be realized.

class Animal:
    pass

How it is used is called instantiation in the class structure.

animal = Animal()

This results in an instance of Animal.

predecessor

One of the properties of classes is that they can be inherited, putting theAnimalclass enrichment under which it is used as a base class:

class Animal:
    property_ = 'Able to think'

    def __init__(self, name, age, value):
        self.name_ = name
        self.age_ = age
        self.val_ = val

In this, property_ is used as a class property without instantiation, while self.name_, self.age_ and self.val_ under __init__ need to be instantiated before they can be used, and here __init__ needs to be passed parameters, in which self is used to refer to the class itself and is not used as a passing parameter.

print(Animal.property_)  # Output: able to think
print(Animal.name_)   # Raise AttributeError error

a = Animal('Ah Hei', 12, 70)
print(a.property_)  # To be able to think
print(a.name_)  # Hei
print(a.age_)  # 12
print(a.val_)  # 70
Copy Code

Animalclass works fine, write anotherMonkeyclass that inheritsAnimalClass.

class Monkey(Animal):
    pass

existMonkeybackward callAnimalclass, which inherits its properties and methods, can also be instantiated, see theMonkeyProperties of the instance.

print(Monkey.property_)  # Class attributes: able to think

m = Monkey('Ah Huang', 15, 40)
print(m.name_)  # Yellow
print(m.age_)  # 15
print(m.val_)  # 40

Of course, it is also possible to inherit from a class and rewrite its existing methods, so here's another definition of aCatClass.

class Cat(Animal):

    def __init__(self, name, age):
        self.name_ = 'I am.' + name
        self.age_ = age

CatClass inheritance rewrites __init__, modifies name_, and removes val_.

print(Cat.property_)  # Class attributes: able to think

c = Cat('Little Flower', 6)
print(c.name_)  # I'm a little flower #
print(c.age_)  # 6
print(c.val_)  # causeAttributeErrorreport an error

For class attributes it still works, missing val_ and calling it again raises an error.

In addition to this, if you want to add attributes to the base class while retaining its properties, you can use thesuper()Processing:

class Fish(Animal):

    def __init__(self, name, age, val, env):
        super().__init__(name, age, val)
        self.env_ = env

When instantiating theFishclass, you need to pass in an extra living environment env parameter:

f = Fish('Koi', 2, 57, 'In the water')
print(f.env_)  # underwater

mro

mroThe meaning ofMethod resolution orderIn class inheritance, it is especially important to understand the order of resolution. For the above classes, you can simply look at the order of mro.

()
# [__main__.Animal, object]

()
# [__main__.Monkey, __main__.Animal, object]

()
# [__main__.Cat, __main__.Animal, object]

()
# [__main__.Fish, __main__.Animal, object]

The order in which mro is parsed is from left to right, with the higher the priority the further to the left you are, so you can see that the first class to be parsed is the current class itself, then the last class it inherits from, and finally the nativeobjectClasses. For all the classes listed above, the inheritance relationships are simple and the order of mro is straightforward.

summarize

To this point this article on Python class mro and inheritance relationship is introduced to this article, more related Python mro content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!