day21-2 类的派生

类的派生

  • 派生:子类中新定义属性的这个过程叫做派生

派生方法一

  • 指明道姓访问某一个类的函数:该方法与继承无关
class People:
    def __init__(self, name, age, gender):
        self.name = name
        self.gender = gender
        self.age = age


class Student(People):
    def choose_course(self):
        print(f'{self.name} is choosing course')


class Teacher(People):
    """由于老师类中有独有的__init__()方法,因此需要声明继承父类的__init__()"""
    def __init__(self, name, age, gender, level):
        
        # 其实就好比于调用了People里的__init__函数,与继承无关
        People.__init__(self, name, age, gender)  
        self.level = level  # 派生

    def teach_course(self):
        print(f'{self.name} is teaching')


stu = Student('tank', '18', 'male')
tea = Teacher('nick', '40', 'male', 1)
print(stu.__dict__)
{'name': 'tank', 'gender': 'male', 'age': '18'}
print(tea.__dict__)
{'name': 'nick', 'gender': 'male', 'age': '40', 'level': 1}

派生方法二

  • 严格以继承属性查找关系
  • super()会得到一个特殊的对象,该对象就是按照继承关系专门用来访问父类中的属性的
  • super().__init__(不用为self传值)
  • super的完整用法是super(自己的类名,self),在python2中需要写完整,在python3中可以简写为super()
class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age


class Student(People):
    def __init__(self, name, age, gender):
        # super(Student, self).__init__(name,age)
        super().__init__(name,age)
        self.gender = gender
        
stud = Student('nick', 18, 'male')
print(stud.__dict__)
{'name': 'nick', 'age': 18, 'gender': 'male'}
posted @ 2019-06-19 15:47  Never&say&die  阅读(114)  评论(0编辑  收藏  举报