类的继承和重用
类的继承和重用
一般继承
# 作业一:定义如下类,并最大程度地重用代码(使用继承或组合,派生+子类重用父类方法)
#
# 老师类
# 学生类
# 分数类
# 课程类
# 日期类
class Date:
def __init__(self, date):
self.date = date
def date(self):
print('your birthday is %s' % self.date)
class People:
def __init__(self, name, age, sex, date):
self.name = name
self.age = age
self.sex = sex
self.date = Date(date)
def eat(self):
print('%s is eating' % self.name)
def drink(self):
print('%s is drinking')
def xiang(self):
print('%s is xianging' % self.name)
def piss(self):
print('%s is pissing' % self.name)
def walk(self):
print('%s is walking' % self.name)
class Score:
def __init__(self, score):
self.score = score
def score(self):
print('your score is %s', self.score)
class Course:
def __init__(self, course):
self.course = course
def course(self):
print('your course is %s' % self.course)
class Student(People):
def __init__(self, name, age, sex, school, score, course):
People.__init__(self, name, age, sex)
self.school = school
self.score = Score(score)
self.course = course
def study(self):
print('%s is studying' % self.name)
class Teacher(People):
def __init__(self, school, name, age, sex, course):
People.__init__(self, name, age, sex)
self.school = school
self.course = Course(course)
def teach(self):
print('% is teaching' % self.name)
if __name__ == '__main__':
p = Student('rendawei', '18', 'male', 'oldboy')
p.study()
super继承
我们在处理类的继承问题时一般都是通过调用父类的函数属性来打到调用父类的方法,但是,如果父类改变的话,需要修改的地方很多,因此,引入super关键字来打到自动传值的效果
class People:
def __init__(self, name, age):
self.name = name
self.age = age
class Teacher(People):
def __init__(self, name, age):
super().__init__(name, age)
if __name__ == '__main__':
egon = Teacher('egon', 73)
print(egon.name)
print(egon.age)
super并不是一个函数,是一个类名,形如super(B, self)事实上调用了super类的初始化函数,产生了一个super对象;
super类的初始化函数并没有做什么特殊的操作,只是简单记录了类类型和具体实例;
super(B, self).func的调用并不是用于调用当前类的父类的func函数;
Python的多继承类是通过mro的方式来保证各个父类的函数被逐一调用,而且保证每个父类函数只调用一次(如果每个类都使用super);
混用super类和非绑定的函数是一个危险行为,这可能导致应该调用的父类函数没有调用或者一个父类函数被调用多次。