Class inherit day24

First, the class inheritance

What is Inheritance: Inheritance is a way to create a new class inherits a class, class properties and methods in the word class

Inherited class is called: the parent class / base class

Inherited class called: word class / derived class

The new class: as long as the inherited object class, the new class is, in python3, the default object class inherits / in python2, the need to display the specified object inheritance

Classic: not inherit object's class, is the classic category, Python3 no Classic, the only Python2 only

class A(object):
    pass

class C:
    pass

# B继承了A,C类
class B(A, C):
    pass

# 类名
print(B.__name__)
# B的父类
print(B.__bases__)

Second, the use of inheritance reduce code redundancy, diamond questions

# 属性的查找顺寻
# 先找对象-->类中找-->父类中找(多继承)-->报错

class Person(object):
    school = 'old_boy'
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
class Teacher(Person):
    pass

class Student(Person):
    pass

# 继承的菱形问题(显示的都继承一个类,不是object类):
# 新式类(py3中全是新式类): 广度优先---从左侧开始,一直往上找,找到菱形的顶点结束(不包括菱形顶点),继续下一个继承的父类往上找,找到菱形的顶点结束(不包括菱形顶点),最后找到菱形顶点

# 经典类(只有py2中才有): 深度优先---从左侧开始,一直往上找,找到菱形的顶点结束(包括菱形顶点)继续下一个继承的父类往上找,找到菱形的顶点结束(不包含菱形顶点)

Third, the father of two ways to reuse

# 第一种方式:父类.__init__方法
class Person:
    def __init__(self, name ,age):
        self.name = name 
        self.age = age
      
class Teacher(Person):
    def __init__(self, name, age, level):
        A.__init(self, name ,age)
        self.level = level
        
# 第二种方式:super()方法
class Person(object):
    school = 'oldboy'
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def study(self):
        print('study....')

class Student(Person):
    school = 'yyyy'
    def __init__(self,name,age,course):
        #super() 会按照mro列表拿到父类对象
        #对象来调用绑定方法,不需要传递第一个参数(self)
        super().__init__(name,age)
        #经典类和新式类
        #经典类中必须这么写(py3中没有经典类),都用上面那种方式写
        # super(Student,self).__init__(name,age)
        self.course=course
    def study(self):
        # Person.study(self)
        super().study()
        # print("%s学生在学习"%self.name)

Guess you like

Origin www.cnblogs.com/17vv/p/11420639.html