首先子类可以继承父类
class FamilyMember:
def __init__(self,name,age): #获取定义的值
self.name = name
self.age = age
def tell(self): #定义的类方法,负责输出
print("我是%s,我%d岁了"%(self.name,self.age))
class Parent(FamilyMember): #子类套用父类
def __init__(self,name,age,salary): #套用父类的__init__的参数,再次基础加上salary新函数
super().__init__(name,age) #继承父类的参数
self.salary=salary #对新加的参数进行定义
def tell(self): #套用父类tell的参数
super().tell() #继承父类的参数
print("我的工资是%d元"%(self.salary)) #新增输出句子
class kids(FamilyMember):
def __init__(self,name,age,score):
super().__init__(name,age)
self.score=score
def tell(self):
super().tell()
print("我的成绩是%d分"%(self.score))
Mum=Parent("妈妈",20,12000)
Mum.tell()
kid1=kids("女儿",18,120)
kid1.tell()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
子类如果只是单纯的继承父类的参数,不进行修改那么直接pass就行
class Parent(FamilyMember):
pass
子类如果要覆写父类的参数,如原本是输出100你要改成200那么直接改
如果只是需要添加,其他的继承那么需要添加super().+类方法
父类:
class FamilyMember:
def tell(self):
print("我是%s,我%d岁了"%(self.name,self.age))
子类:(覆写)
class Parent(FamilyMember):
def tell(self):
print("我的工资是%d元"%(self.salary))
输出
我的工资是xxx元
子类:(继承)
class Parent(FamilyMember):
def tell(self):
super().tell()
print("我的工资是%d元"%(self.salary))
输出
我是xx,我xx岁了
我的工资是xxx元
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24