继承

多个类有一些共性(方法),并且这个类对于他们有些公共概念,这时候可以做一个父类

为什么构建类,因为这个类有行为承担

在设计思想上,先有子再有父亲

从编码角度上,先有父亲再有子

  1. isinstance(对象,类型)判断对象和类型关系

  2. issubclass(类型,类型)判断类和类之间关系

  3. type()对象和类型关系

    class Dog(Animal):
        def run(self):
            print("跑")
    
    
    class Bird(Animal):
        def fly(self):
            print("飞")
    
    
    a01 = Animal()
    d01 = Dog()
    b01 = Bird()
    
    print(isinstance(a01, Animal))
    print(isinstance(d01, Animal))
    print(issubclass(Dog, Animal))
    print(type(b01) == Bird)
    print(type(b01) == Animal)
    
  4. 子类没有构造函数,可以直接使用父类的方法,但是要用super().__init__()

    class Person:
        def __init__(self, name=None, age=None):
            self.name = name
            self.age = age
    
    class Student(Person):
        # 调用父类构造参数时,子类也要传递相应参数给父类
        def __init__(self, name, age, score=None):
            # name和age是父类构造方法参数,
            super().__init__(name, age)
            # 子类实例变量
            self.score = score
    
        def score(self):
            print("学生成绩")
    
    s1 = Student('李小凤', 23, 100)
    print(s1.name, s1.age)
    
  5. 子类有构造函数,会覆盖父类构造函数

    class Person:
        def __init__(self, name=None, age=None):
            self.name = name
            self.age = age
    
    class Student(Person):
        # 调用父类构造参数时,子类也要传递相应参数给父类
        def __init__(self, name, age, score=None):
            # name和age是父类构造方法参数,super调用父类构造方法
            super().__init__(name, age)
            # 子类实例变量
            self.score = score
    
        def score(self):
            print("学生成绩")
    
    s1 = Student('李小敏', 23, 100)
    print(s1.name, s1.age)
    
posted on 2020-12-26 22:48  xiao小胡子  阅读(75)  评论(0)    收藏  举报