Inheritance and polymorphism

1, Inherit

Inheritance is a way to create new classes. In python, a new class can inherit one or more parent classes, the new class can be called a child class or parent class, and the inherited class can be called a parent class or base class.

Subclasses can use properties or methods in the parent class

It solves the problem of code redundancy between classes

In python2, the children and grandchildren who inherit the objcet class are called new classes, and those who do not inherit are called classic classes

In Python 3, there is no distinction between classic classes and new classes. They are all new classes

 

 

 

Single inheritance

Inheriting only one parent class is called singleton inheritance

Attribute search under single inheritance

class Foo():
    def f2(self):
        print('from Foo')
    def f1(self):
        print('from Foo')

class Bar(Foo):
    def f1(self):
        print('from f1')

# When the attribute or method is in a subclass, the of the subclass is used. If it is not found, it will be found in the parent class, and an error will be reported if it is not found in the parent class
obj = Bar()
obj.f1()  # from f1 
obj.f2()  # from Foo
obj.f3()  # report errors

  


# Exercise 1

class Foo: def f1(self): print('Foo.f1') def f2(self): # print('Foo.f2') self.f1() class Bar(Foo): def f1(self): print('Bar.f1') obj = Bar() # {} obj.f2()
# Exercise 2 class Foo: def __f1(self): # _Foo__f1() print('Foo.f1') def f2(self): # print('Foo.f2') self.__f1() # _Foo__f1() class Bar(Foo): def __f1(self): # # _Bar__f1() print('Bar.f1') obj = Bar() # {} obj.f2()

 

 

 

   

Multiple inheritance

Inheriting multiple parent classes is called multiple inheritance

Attribute search under multi inheritance

Attribute search under multi inheritance is generally divided into search by breadth and search by depth

New classes are searched by breadth  

class G:
    def test(self):
        print('from A')


class E(G):
    def test(self):
        print('from B')
    pass

class F(G):
    def test(self):
        print('from C')
    pass


class B(E):
    def test(self):
        print('from D')
    pass

class C(F):
    def test(self):
        print('from B')
    pass
class D(G):
    def test(self):
        print('from B')
    pass

class A(B,C,D): def test(self): print('from A') pass print(F.mro()) # Search order [< class' _main _. B '>, < class' _main _. E' >, < class' _main _. C '>, < class' _main _. F' >, < class' _main _. D '>, < class' _main _. G' >, < class' object '>] f1 = F() f1.test()

  

 

 

       

Classic classes are searched in order of depth

class G:
    def test(self):
        print('from A')


class E(G):
    def test(self):
        print('from B')
    pass

class F(G):
    def test(self):
        print('from C')
    pass


class B(E):
    def test(self):
        print('from D')
    pass

class C(F):
    def test(self):
        print('from B')
    pass
class D(G):
    def test(self):
        print('from B')
    pass

class A(B,C,D): def test(self): print('from A') pass print(F.mro()) # Search order [< class' _main _. B '>, < class' _main _. E' >, < class' _main _. G '>, < class' _main _. C' >, < class' _main _. F '>, < class' _main _. D' >, < class' object '>] f1 = F() f1.test()

  

 

 

 

        

2, Use of super() and mro lists

super() application

             super() will return a special object, which will refer to the mro list of the class that initiated the attribute search, and search the attribute in the parent class of the current class in turn.

        mor list

mro() will display the inheritance order of classes. The mor list will search for the parent class from left to right until the first class matching this attribute is found. Class. mro() will view the mro list

class B:
    def test(self):
        print('B---->test')


    def aaa(self):
        print('B---->aaa')

class A:
    def test(self):
        print('A---->test')
        super().test()



class C(A, B):
    def aaa(self):
        print('C----->aaa')


c = C()
c.test()  # Print result: a --- > test B --- > test
print(C.mro())

 

3, Polymorphism and polymorphism

What is polymorphism

Polymorphism means that a class of things has multiple forms (an abstract class has multiple subclasses, so the concept of polymorphism depends on inheritance)

For example, there are many forms of animals: people, dogs and pigs

      

# Polymorphism: multiple forms of the same thing. Animals are divided into humans and pigs (in terms of definition)
# Mode 1
class Animal:
    def run(self):
        raise Excecption('Subclasses must implement this method')


class People(Animal):
    def run(self):
        print('People are walking')


class Pig(Animal):
    def run(self):
        print('pig is walking')


class Dog(Animal):
    def run(self):
        print('dog is running')


peo = People()
pig = Pig()
d = Dog()

peo.run()
pig.run()
d.run()

  

# Mode 2
import abc


class Animal(metaclass=abc.ABCMeta):  # The same thing: Animals
    @abc.abstractmethod
    def talk(self):
        pass


class People(Animal):  # One of the forms of animals: man
    def talk(self):
        print('say hello')


class Dog(Animal):  # Animal form 2: dog
    def talk(self):
        print('say wangwang')


class Pig(Animal):  # Animal form 3: Pig
    def talk(self):
        print('say aoao')

  

 

What is polymorphism

Polymorphism means that functions with different functions can use the same function name, so that functions with different contents can be called with one function name. In object-oriented methods, polymorphism is generally expressed as follows: send the same message to different objects, and different objects receive it                        It will produce different behaviors (i.e. methods). That is, each object can respond to a common message in its own way. The so-called message refers to calling functions. Different behaviors refer to different implementations, that is, executing different functions.

    

#Polymorphism: a calling method with different execution effects (polymorphism)
def func(obj):
    obj.run()
 
func(peo1)
func(pig1)
func(d1)
 
 
# peo1.run()
# pig1.run()
 
 
# Polymorphism depends on: Inheritance
##Polymorphism: define a unified interface,
def func(obj): #The obj parameter has no type restrictions. Different types of values can be passed in
    obj.run() #The call logic is the same, but the execution result is different
 
func(peo1)
func(pig1)
 
func(d1)

Summary  

Polymorphism: multiple forms of the same thing. Animals are divided into humans and pigs (in terms of definition)   Polymorphism: a calling method with different execution effects (polymorphism)

 

3, Why use polymorphism (the benefits of polymorphism)

(1) increased program flexibility
Respond to changes with invariance. Regardless of the ever-changing objects, users call them in the same form, such as func(animal)
  

(2) increased program scalability
By inheriting the animal class, a new class is created. Users do not need to change their own code, or use func(animal) to call

 

Posted by redrage on Mon, 06 Dec 2021 14:41:36 -0800