当前位置:网站首页>子类调用父类的同名方法和属性
子类调用父类的同名方法和属性
2022-07-01 06:13:00 【北山啦】
Python面向对象中,利用子类调用父类的同名方法和属性。
首先我们定义了两个父类,Master
和School
# @author: 北山啦
# FileName: 12子类调用父类的同名方法
# @time: 2022/6/5 14:54
#父类Master
class Master():
def __int__(self):
self.kongfu = '[古法煎饼果子配方]'
def make_cake(self):
print(f'运用{
self.kongfu}制作煎饼果子')
#父类School
class School():
def __init__(self):
self.kongfu = '[黑马煎饼果子配方]'
def make_cake(self):
print(f'运用{
self.kongfu}制作煎饼果子')
对于相同属性和方法的父类,子类如何来调用呢
在这里,定义Prentice类,继承了Master和School类,添加了和父类同名属性和方法
- 调用子类的属性和方法
如果调用了父类的属性和方法,父类属性会自动掩盖子类属性,股灾调用属性前,先调用自己子类的初始化
class Prentice(School,Master):
def __init__(self):
self.kongfu = '[独创煎饼果子配方]'
def make_cake(self):
self.__init__
print(f'运用{
self.kongfu}制作煎饼果子')
- 调用父类属性和方法
如果调用父类方法,但是为了保障调用到的是父类的属性,必须在方法前调用父类的初始化
def make_master_cake(self):
Master.__init__(self)
Master.make_cake(self)
def make_school_cake(self):
School.__init__(self)
School.make_cake()
完整代码
# @author: 北山啦
# FileName: 12子类调用父类的同名方法
# @time: 2022/6/5 14:54
class Master():
def __int__(self):
self.kongfu = '[古法煎饼果子配方]'
def make_cake(self):
print(f'运用{
self.kongfu}制作煎饼果子')
class School():
def __init__(self):
self.kongfu = '[北山啦煎饼果子配方]'
def make_cake(self):
print(f'运用{
self.kongfu}制作煎饼果子')
class Prentice(School, Master):
def __init__(self):
self.kongfu = '[独创煎饼果子配方]'
'''如果调用了父类的属性和方法,弗列属性会自动掩盖子类属性,股灾调用属性前,先调用自己子类的初始化'''
def make_cake(self):
# self.__init__
print(f'运用{
self.kongfu}制作煎饼果子')
'''调用父类方法,但是为了保障调用到的是弗列的属性,必须在方法前调用父类的初始化'''
def make_master_cake(self):
Master.__init__(self)
Master.make_cake(self)
def make_school_cake(self):
School.__init__(self)
School.make_cake()
beishan = Prentice()
print(beishan.make_cake())
print(beishan.make_master_cake())
print(beishan.make_school_cake())
边栏推荐
- Linux closes the redis process SYSTEMd+
- 【ManageEngine卓豪】局域网监控的作用
- 相同区域 多源栅格数据 各个像元行列号一致,即行数列数相同,像元大小相同
- 解决麒麟V10上传文件乱码问题
- Thesis learning record essay multi label lift
- LED lighting used in health lighting
- srpingboot security demo
- skywalking集成nacos动态配置
- Servlet
- Database problems, how to optimize Oracle SQL query statements faster and more efficient
猜你喜欢
随机推荐
OpenGL es: (4) detailed explanation of EGL API (Continued)
Stack Title: parsing Boolean expressions
Solve the problem of garbled files uploaded by Kirin v10
扩散(多源广搜)
Multi label lsml for essay learning records
Flink实战--多流合并
Differences between in and exists in MySQL
libpng12.so. 0: cannot open shared object file: no such file or directory
【ManageEngine卓豪 】助力世界顶尖音乐学院--茱莉亚学院,提升终端安全
1034 Head of a Gang
ArcServer密码重置(账号不可以重置)
手把手教你实现一个深度学习框架...
69 Cesium代码datasource加载geojson
Understanding of C manualresetevent class
Distributed lock implementation
jdbc-连接池
HCM Beginner (IV) - time
HDU - 1501 Zipper(记忆化深搜)
ForkJoin和Stream流测试
栈题目:解析布尔表达式