One of the three characteristics of object-oriented: Inheritance

First, what is inherited?

  Inheritance is a relationship between two objects is described, what is the relationship between what:

The new class can inherit one or more parent class is called the parent class has a base class or superclass, the new type is called a derived class or subclass, single and multiple inheritance in python

class Base: 
    Ser = " This is a base class " 
    DEF show_info (Self):
         Print (self.ser) 

    DEF make_money (Self):
         Print ( " ! hey hard to force day " )
         # specify the parent class-bit Base 

class Subclass ( Base):
     Pass 
obj = Subclass () # even if nothing class can use the parent has some centralized content 
obj.make_money ()
 Print (obj.ser)

  In the procedure, described in inheritance relationship between classes and, for example: a succession of b, a b can be used directly in existing methods and properties

 

View Inheritance:

print (Subclass .__ bases__) 

Second, abstraction and inheritance: the abstract is not clear, not specific, very confused
  abstract pulling out similar or more like parts: human, pig, dog three classes more like part of the extract into a parent class. Animal
 correct use of inheritance:
  1, the first abstract and then inherit
  2, inheriting an already existing class, extend or modify the original function
Inheritance: is based on the abstract result, the programming language to implement it, certainly is the first experience of this abstract process in order to express the abstract structure by way of inheritance.
# Extracting the same portions of the teachers and students form class person 
class the Person:
     DEF  the __init__ (Self, name, Age, Gender): 
        the self.name = name 
        self.age = Age 
        self.gender = Gender
     DEF say_hi (Self):
         Print ( " name:% S, Gender:% S, Age:% S " % (self.name, self.gender, self.age))
 class Teacher (the Person): #   calls to reduce the repetitive code 
    # DEF Teaching (Self ): 
        Print ( " ! drowsy teacher in the class ... " ) 
T1 = teacher ( "JSON " , " FEMALE " , 20 is ) 
t1.say_hi () 

class Student (the Person): # calling features the same properties 
        Pass 
STU1 = Student ( " the Reso " , " MALE " , 18 is ) 
stu1.say_hi () 


" call subclass the parent of the same age, name, gender attributes, making the code less repeat "

 

Third, derived

  When a subclass occurred with different content parent class, subclass it is called a derived class;

Usually sub-class will write some new code, and the parent can not be exactly the same, that is usually derived class, the derived class refers to a subclass

class Person:
    def say_hi(self):
        print("hello")

class Student(Person):
    def say_hi(self):
        print("hello world!")

stu = Student()
stu.say_hi()

Fourth, covering:

  Also known rewritten: overrides when subclasses appears exactly the same name as the parent class property or method

  The search order priority subclass attributes, this behavior is also known as覆盖

Fifth, find the order of attributes:

  The object itself - where the class >> - >> find parent - the parent class's parent class >> - >> Object (Object)

class A:
    text="heihei"
class B(A):
    text="haha"
class C(B):
    text="dogdog"
    pass
b=B()
b.text="are you ok"
print(b.text)

c=C()
c.text="aabb"
print(c.text)

>>

are you ok
aabb

 

 

Sixth, the content of the subclass access to the parent class 

  Syntax: call super ()

Mode 1: 
Super (current class name, self) you want to transfer the property or method of the parent class. 
Mode 2: Super () new syntax properties or methods of the parent class you want to tune # to access way 2 py3 of the most commonly used. the way
Mode 3: class name of the parent class property or method you want to tune (Self). 

# Mode 3 has nothing to do with inheritance
class the Parent: 
    text = " abc " 
    DEF say_something (Self):
         Print ( " Anything " )
 class Sub (the Parent):
     DEF show_info (Self):
         # Print (Super (Sub, Self) .text) 
        # Super (Sub, Self ) .say_something () 
        # new syntax for accessing mode 2 py3 the most common way to 
        Print (Super (). text) 
        Super (). say_something () 
        # ways to directly specify the class name to call 3 
        # Print (Parent.text) 
        # the Parent. say_something (Self) 
Sub = Sub () 
sub.show_info ()


 >>>
    why?

Key:

  When you inherit a class and some appear, and covers __init__ method of the parent class, you must first call the parent class line in the initialization method

Initialization, passing in the required parameters parent (the scene when the application requires specific restrictions)

 

class Student (the Person): 

DEF the __init __ (Self, name, Gender, Age, number):
Super () .__ the init __ attributes (name, gender, age) # class front extra number must be used to define
self.number = number

 

  Demand: restriction element may need to implement a type of container (dictionary, list, tuple, set, the string

class of MyList (List):
     DEF  the __init__ (Self, ELEMENT_TYPE): 
        . Super () the __init__ () # initialization method is called the parent class to complete the basic initialization 
        self.element_type = ELEMENT_TYPE 

    DEF the append (Self, Object):
         "" " 
        : param object: is the element to be stored 
        : return: no 
        "" " 
        IF of the type (Object) == self.element_type:
             # we need here to visit the parent class append function to do the real storage operation 
            super (MyList, self). the append (Object)
         the else :
             Print ( " Sorry SIR, IS not you Element of the type% S " %self.element_type) 


# create the element type is specified to be stored 
m = MyList (int)
 # when you have demand, is the need to create the object what to do with the thing would expect initialization method
 
m.append ( 1 )
 Print ( m [0]) 
m.append ( " 121212 " )

   When you use super () function, Python will continue to search for the next class in the MRO list. If each redefined method using a unified super () and call it only once,

Then the flow of control will eventually traverse a complete list of MRO, each method will only be called once

(Note Note Note: use all the attributes of super calls, are looking back from the MRO list of current location, do not look at the code went through inheritance, MRO must see list)

# A no inheritance B, but will be based within A super C.mro () continue to the next looking for 
class A:
     DEF the Test (Self): 
        Super () the Test (). 
Class B:
     DEF the Test (Self):
         Print ( ' from B ' )
 class C (A, B):
     Pass 

C = C () 
c.test () # print result: from B 


Print (C.mro ())
 # [<class'. __ in __main C '>, <class' __main __. A '>, < class' __main __. B'>, <class' object '>]

 

Seven, a combination of:

  Means: In one class to another class of the object as the combined data class attribute called

  For example: students have cell phones, game characters have certain skills (that is, what what)

Combined purposes: to reuse existing code is

 

When to use inheritance: analysis of the relationship between two classes, in the end is not: What is the relationship between what

When to use a combination of: if there is no significant relationship between the two classes, do not belong to the same

 

Eight diamond inheritance:

 

Added: new-style class and Classic

Python3 in any class are inherited directly or indirectly Object

New class, any explicit or implicit object inherits from class to the new class is called, all of the new class to python3 

Classic, is neither a subclass of Object, occurs only in python2 

菱形继承
class A:
    j = 1
    pass

class B:
    # j = 2
    pass

class C(A):
    # j = 3
    pass

class D(A):
    j = 4
    pass

class E(B,C,D):
    # j = 5
    pass

d = E()
print(d.j)

When there is a diamond inheritance, the new class, the first depth, when faced with a common parent class on breadth

The new category is depth-first

 

 

  

 

 

 

 

 

 

 




  


 

 

Guess you like

Origin www.cnblogs.com/Gaimo/p/11247426.html