子类派生的新方法中重用父类的功能
继承实现原理(菱形问题)
多继承代码规范
组合
子类派生的新方法中重用父类的功能
class People:
school = '上海校区'
def __init__(self,name,age,sex)
self.name = name
self.age = age
self.sex = sex
class Student(people):
def choose(self)
print('%s 选课成功' %self.name)
class Teacher(People):
def __init__(self,name,age,sex,level):
People.__init__(self,name,age,sex,)
self.levle = level
def course(self):
print('%s 正在打分'%self.name)
s = Student('liu',18,'male')
print(s.__dict__) # {'name': 'liu', 'age': 18, 'sex': 'male'}
print(s.name) # liu
s.choose() # liu 正在选课
t= Teacher('egon',18,'male',8999,9000000)
print(t.__dict__) #{'name': 'egon', 'age': 18, 'sex': 'male', 'level': 8999, 'salary': 9000000}
People.init(self)直接调用,不继承也可以
super调用 总体代码和上面一样,再敲一遍
class People:
school = '天上人间'
def __init__(self,name,age,sex)
self.name = name
self.age = age
self.sex = sex
class Student(People):
def choose(self)
print('%s 选课中' %self.name)
class Teacher(People): # 使用super调用,必须继承
def __init__(self,name,age,sex,level,salary)
# super(Teacher, self).__init__() # 可省略Teacher,self
super().__init__(name,age,gender) # 且不需传self
self.level = level
self.salary = salary
def course(self):
print('%s 打分'%self.name)
s = Student('liu',18,'male')
print(s.__dict__) # {'name': 'liu', 'age': 18, 'sex': 'male'}
print(s.name) # liu
s.choose() # liu 正在选课
t= Teacher('egon',18,'male',8999,9000000)
print(t.__dict__) #{'name': 'egon', 'age': 18, 'sex': 'male', 'level': 8999, 'salary': 9000000}
# 调用同上
==继承实现原理(菱形问题)
一个子类继承的多分枝最终汇聚一个非object的类上
class G: # 在python2中,未继承object的类及其子类,都是经典类
def test(self):
print('from G')
class E(G):
def test(self):
print('from E')
class F(G):
def test(self):
print('from F')
class B(E):
def test(self):
print('from B')
class C(F):
def test(self):
print('from C')
class D(G):
def test(self):
print('from D')
class A(B,C,D):
def test(self):
print('from A')
obj = A() # A->B->E->C->F->D->G->object 按照这个顺序也就是mro列表继承
多继承规范
涉及到多继承 可用mixins机制,如下
class Vehicle:
pass
class FlyableMixin:
def fly(self):
print('flying')
class CivilAircraft(FlyableMixin,Vehicle):
pass
class Helicopter(FlyableMixin,Vehicle):
class Car(Vehicle):
pass
组合,表示有,继承是 是 的关系,比如 人是动物,组合是 有 的关系,比如 我有手机,
class People:
school = '天上人间'
def __init__(self,name,age,gender)
self.name = name
self.age = age
self.gender = gender
class Student(People):
def choose(self):
print('%s 选课'%self.name)
class Teacher(People):
def __init__(self,name,age,gender,level,salary)
super().__init(name,age,gender)
self.level = level
self.gender = gender
def score(self):
print('%s正在打分'%self.name)
class Course:
def __init__(self,name,price,proide)
self.name = name
self.price = price
self.proide = proide
def tell(self):
print('课程信息<%s:%s:%s>'%s(self.name,self.price,self.proide)
python = ('全栈开发',20000,'6mons')
linux = ('运维',19999,'5mons')
s1 = Student('liu',18,'male')
t1 = Teacher('egon',18,'male')
s1.course = []
s1.course.append(python)
s1.course.append(linux)
for course_obj1 in s1.course:
course_obj1.tell() #课程信息<开发:19999:6mons> 课程信息<运维:19998:5mons>