查看一个类继承了哪些类可以用__bases__方法查看
class People:
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def foo(self):
print('from parent')
class Teacher(People):
def __init__(self,name,age,sex,salary,level):
People.__init__(self,name,age,sex) #指名道姓地调用People类的__init__函数
在python3中
super().__init__(name,age,sex) #调用父类的__init__的功能,实际上用的是绑定方法
在python2中
super(Teacher,self).__init__(name,age,sex)
self.salary=salary
self.level=level
def foo(self):
super().foo()
print('from child')
t=Teacher('egon',18,'male',3000,10)
print(t.name,t.age,t.sex,t.salary,t.level)
t.foo()
指名道姓的调用方式有如下应用场景:
class Alive:
def __init__(self,name,age):
print('Alive--------------->')
self.name=name
self.age=age
class People:
def __init__(self,sex):
print('People--------------->')
self.sex=sex
class Teacher(People,Alive):
def __init__(self,name,age,sex,salary,level):
Alive.__init__(self,name,age)
People.__init__(self,sex)
self.level=level
self.salary=salary
def foo(self):
print('-----》')
t=Teacher('egon',18,'male',300,10)
# print(t.name,t.age,t.sex,t.salary,t.level)
t.foo()