Object-oriented: Inheritance

One: What is object-oriented inheritance?

Compare the official statement is:

Inheritance (English: inheritance) is a concept of object-oriented software technology among. If a category A "inherited from" Another category B, put the A is called "sub-category B", and B is called the "father of category A" can also be called "B of A is a superclass." Inheritance can have various subcategories such properties and methods of the parent class, without the need to write the same code again. While Reiko category inherit the parent class, you can re-define certain attributes, and override some methods, properties and methods of the original parent category that is covered, so to get the parent category different functions. In addition, for the subcategory additional new properties and methods it is also common practice. General static object-oriented programming language, inherited a static, meaning it has been decided to compile in the behavior of sub-categories, can not expand in the implementation period.

Literally means: his father's footsteps, the legal successor of the family property, that is, if you are an only child, and you are very obedient, nothing else, you will inherit your parents all possessions, all their property would (except prodigal child) used by you .

So it inherited with a look at an example:

img View Code

Inherited little is obvious:

1, an increase of the class coupling (coupling not appropriate, should be fine).

2, reducing the repeated code.

3, makes the code more standardized, rationalized.

Category 2 inheritance.

On the above example:

Aminal called the parent class, the base class, superclass.
Person Cat Dog: subclass, derived class.
Inheritance: can be divided into single inheritance, multiple inheritance .

We should add species (inherited required) classes in python:

There are two classes in python2x version:
  ⼀ a called Classic before python2.2 ⼀ straight Using the classic root base class class class in classic if nothing to write....
  ⼀ called a new category in. python2.2 appeared after the new class. the new features is the root class is the base class for the object class.
python3x version is only one class:
python3 Use of manipulation are the new class . If the base class who do not inherit the class object inherits by default

Third, the single inheritance.

3.1 class name, object to perform the parent class method

img Class name, object calls the parent class method, respectively

3.2 execution order

img Execution order

3.3 classes and parent classes while performing methods

method one:

If you want to perform the func methods of the parent class, subclass this method and night use, then write in the method of the subclass:

.FUNC parent class (object other parameters)

for example:

Copy the code

class Aniaml(object):
    type_name = '动物类'
    def __init__(self,name,sex,age):
            self.name = name
            self.age = age
            self.sex = sex

    def eat(self):
        print('吃东西')

class Person(Aniaml):
    def __init__(self,name,sex,age,mind):
        '''
        self = p1
        name = '春哥'
        sex = 'laddboy'
        age = 18
        mind = '有思想'
        '''
        # Aniaml.__init__(self,name,sex,age)  # 方法一
        self.mind = mind

    def eat(self):
        super().eat()
        print('%s 吃饭'%self.name)
class Cat(Aniaml):
    pass

class Dog(Aniaml):
    pass

# 方法一: Aniaml.__init__(self,name,sex,age)
# p1 = Person('春哥','laddboy',18,'有思想')
# print(p1.__dict__)

# 对于方法一如果不理解:
# def func(self):
#     print(self)
# self = 3
# func(self)

Copy the code

Method Two:

Using super, super (). Func (parameter)

Copy the code

class Aniaml(object):
    type_name = '动物类'
    def __init__(self,name,sex,age):
            self.name = name
            self.age = age
            self.sex = sex

    def eat(self):
        print('吃东西')

class Person(Aniaml):
    def __init__(self,name,sex,age,mind):
        '''
        self = p1
        name = '春哥'
        sex = 'laddboy'
        age = 18
        mind = '有思想'
        '''
        # super(Person,self).__init__(name,sex,age)  # 方法二
        super().__init__(name,sex,age)  # 方法二
        self.mind = mind

    def eat(self):
        super().eat()
        print('%s 吃饭'%self.name)
class Cat(Aniaml):
    pass

class Dog(Aniaml):
    pass
# p1 = Person('春哥','laddboy',18,'有思想')
# print(p1.__dict__)

Copy the code

Single inheritance exercises:

img View Code

Fourth, multiple inheritance

Copy the code

class ShenXian: # 神仙
    def fei(self):
        print("神仙都会⻜")
class Monkey: # 猴
    def chitao(self):
        print("猴⼦喜欢吃桃⼦")
class SunWukong(ShenXian, Monkey): # 孙悟空是神仙, 同时也是⼀只猴
    pass
sxz = SunWukong() # 孙悟空
sxz.chitao() # 会吃桃⼦
sxz.fei() # 会⻜

Copy the code

  At this point, the Monkey King is the only monkey ⼀ submenus, but also ⼀ a god. That Monkey inherited these two categories. Monkey natural coloring can Perform these two classes of Remedies. Using multiple inheritance is simple also very good understanding, but multiple inheritance, there are so ⼀ a problem. when two ⽗ class appeared in the same name Remedies time. then how to do it? then it comes to how to find such a ⼀ ⽗ class methods for the camera question. that MRO (method resolution order) problem. ⼀ in python this is a very complex issue because the Use of different versions of python manipulation are different algorithms to complete the MRO.

We should add species (inherited required) classes in python:

There are two classes in python2x version:
  ⼀ a called Classic before python2.2 ⼀ straight Using the classic root base class class class in classic if nothing to write....
  ⼀ called a new category in. python2.2 appeared after the new class. the new features is the root class is the base class for the object class.
python3x version is only one class:
python3 Use of manipulation are the new class . If the base class who do not inherit the class object inherits by default

Multiple inheritance is 4.1 Classic

Although there is no Classic in python3 in. But the classic class MRO'd better learn ⼀ school. This is ⼀ kind of tree traversal ⼀ most straightforward cases. We can put in a class inheritance hierarchy in python the class inheritance tree structure into ⼀ be dpi, the code:

img The sample code

Mro can deal with this drawing:

img

Inheritance diagrams have. How it into ⾏ find it? Remember ⼀ principle. In the classic category are recorded using a depth-first traversal ⽅ case. What is depth-first. ⼀ road is coming to an end. Then come back continue to look for to record the next one.

img

Figure each circle is ready to send egg address. Arrows and lines displayed in black and line table. That tells you the order to send the eggs into the right to send in the most under-connector ⾯ R. and must be left. Then how to send it?

img

As shown in FIG. Definitely in that order 123456 to send. That this order is called depth-first traversal. ⽽ if it is 142,356? This is called Wide-of-first traversal. Okay. So much depth-first. Then ⾯ the map on how to find it? What is MRO? very simple. Remember that. scratch from left to right. ⼀ road ran head, then go back. continue ⼀ road went head. MRO algorithm is the classic class .

Class MRO: Foo-> H -> G -> F -> E -> D -> B -> A -> C. You got it?

4.2 new class of multiple inheritance

4.2.1 mro sequence

MRO is an ordered list L, when the class is created it is calculated.
General formula is:

mro(Child(Base1,Base2)) = [ Child ] + merge( mro(Base1), mro(Base2), [ Base1, Base2] )(其中Child继承自Base1, Base2)

If a base class to inherit: class B (A)
time sequence B is mro

mro( B ) = mro( B(A) )
= [B] + merge( mro(A) + [A] )
= [B] + merge( [A] + [A] )
= [B,A]

If the successor to the plurality of base classes: class B (A1, A2, A3 ...)
this time sequence B mro

mro(B) = mro( B(A1, A2, A3 …) )
= [B] + merge( mro(A1), mro(A2), mro(A3) ..., [A1, A2, A3] )
= ...

The results as a list, a list of at least one element i.e. the class itself, as in the examples [A1, A2, A3]. merge operation is a core C3 algorithm.

4.2.2 headers and footers.
Header:
  the first element of the list

Footer:
  element other than the head of a list of tables set (which may be empty)

Example
  List: [A, B, C]
  header is A, B and C footer

4.2.3 Operation between listing +
+ operator:

[A] + [B] = [A, B]
(the default calculations shown)
---------------------

merge operation example:

Copy the code

如计算merge( [E,O], [C,E,F,O], [C] )
有三个列表 :  ①      ②          ③

1 merge不为空,取出第一个列表列表①的表头E,进行判断                              
   各个列表的表尾分别是[O], [E,F,O],E在这些表尾的集合中,因而跳过当前当前列表
2 取出列表②的表头C,进行判断
   C不在各个列表的集合中,因而将C拿出到merge外,并从所有表头删除
   merge( [E,O], [C,E,F,O], [C]) = [C] + merge( [E,O], [E,F,O] )
3 进行下一次新的merge操作 ......
--------------------- 

Copy the code

img

Calculation mro (A) by:

Copy the code

mro(A) = mro( A(B,C) )

原式= [A] + merge( mro(B),mro(C),[B,C] )

  mro(B) = mro( B(D,E) )
         = [B] + merge( mro(D), mro(E), [D,E] )  # 多继承
         = [B] + merge( [D,O] , [E,O] , [D,E] )  # 单继承mro(D(O))=[D,O]
         = [B,D] + merge( [O] , [E,O]  ,  [E] )  # 拿出并删除D
         = [B,D,E] + merge([O] ,  [O])
         = [B,D,E,O]

  mro(C) = mro( C(E,F) )
         = [C] + merge( mro(E), mro(F), [E,F] )
         = [C] + merge( [E,O] , [F,O] , [E,F] )
         = [C,E] + merge( [O] , [F,O]  ,  [F] )  # 跳过O,拿出并删除
         = [C,E,F] + merge([O] ,  [O])
         = [C,E,F,O]

原式= [A] + merge( [B,D,E,O], [C,E,F,O], [B,C])
    = [A,B] + merge( [D,E,O], [C,E,F,O],   [C])
    = [A,B,D] + merge( [E,O], [C,E,F,O],   [C])  # 跳过E
    = [A,B,D,C] + merge([E,O],  [E,F,O])
    = [A,B,D,C,E] + merge([O],    [F,O])  # 跳过O
    = [A,B,D,C,E,F] + merge([O],    [O])
    = [A,B,D,C,E,F,O]
--------------------- 

Copy the code

C3 is the common heritage of stay to the end we went to multiple classes associate the resulting so we can also come to see the relevant law from the figure .. but if no such thing as a common inheritance. That will get accustomed almost as deep traversal is on it

Guess you like

Origin www.cnblogs.com/qidaii/p/11373594.html