继承:
父类(基类)
子类(派生类)
子类继承父类继承了什么?
变量(数据属性)
实例属性
方法
方法重写
class Father(object):
address='xian'
# 定义了一个信息方法
def info(self):
print('this is a father method')
def __init__(self,name,age):
self.name=name
self.age=age
class Son(Father):
def __init__(self,name,age,score):
# 实现子类继承了父类的属性super用来调用父类中的方法
super().__init__(name,age)
# 定义一个得分变量
self.score=score
# 定义一个show方法返回的是类本身自己
def show(self):
print('name is {0},and age is {1},and score is{2}'.format(self.name,self.age,self.score))
# 定义一个info(信息)方法
def info(self):
print('this is a son method')
# 分别给name、age和socore定义值并赋值给son
son=Son(name='wuya',age=18,score=90)
# 输出son
son.show()
print(son.address)
son.info()
结果:
name is wuya,and age is 18,and score is90
xian
this is a son method
继承顺序:
1、从上到下
前提条件:
单个类继承
子类重写了父类的方法
2、从左到右
前提条件:
子类继承了多个类
# 注意 子类可以继承'多个父类',但是'多个父类'必须是同级关系
class Person(object):
pass
class Father(Person):
def __init__(self,name,age):
self.name=name
self.age=age
def funf(self):
return 'father'
class Mother(object):
def funM(self):
return 'mother'
class Son(Mother,Father):
def __init__(self,name,age,score):
# super用来调用父类中的方法
super().__init__(name,age)
# 定义一个得分变量
self.score=score
def show(self):
print('name is {0},and age is {1},and score is{2}'.format(self.name,self.age,self.score))
son=Son(name='wuya',age=18,score=90)
son.show()
print(son.funf(),son.funM())
# 通过线性方式调用子类中父类的方法
print(Son.mro())
结果:
name is wuya,and age is 18,and score is90
father mother
[<class '__main__.Son'>, <class '__main__.Mother'>, <class '__main__.Father'>, <class '__main__.Person'>, <class 'object'>]