当前位置:网站首页>子类调用父类的同名方法和属性
子类调用父类的同名方法和属性
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())
边栏推荐
猜你喜欢

解决麒麟V10上传文件乱码问题

Skywalking integrated Nacos dynamic configuration

68 cesium code datasource loading czml

TiDB单机模拟部署生产环境集群(闭坑实践,亲测有效)

What if the data in the cloud disk is harmonious?

skywalking集成nacos动态配置

three.js小结

Freeswitch dial the extension number

69 Cesium代码datasource加载geojson
![[note] e-commerce order data analysis practice](/img/03/367756437be947b5b995d5f7f55236.png)
[note] e-commerce order data analysis practice
随机推荐
Treasure taking from underground palace (memory based deep search)
1034 Head of a Gang
地宫取宝(记忆化深搜)
Save data in browser to local file
Record currency in MySQL
Infinite horizontal marble game
ABP 学习解决方案中的项目以及依赖关系
栈题目:解析布尔表达式
机械臂速成小指南(六):步进电机驱动器
Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills
JDBC database operation
Thoughts on a "01 knapsack problem" expansion problem
让田头村变甜头村的特色农产品是仙景芋还是白菜
skywalking集成nacos动态配置
Arcserver password reset (account cannot be reset)
Recueillir des trésors dans le palais souterrain (recherche de mémoire profonde)
srpingboot security demo
68 cesium code datasource loading czml
3D打印机穿线:5种简单的解决方案
【ITSM】什么是ITSM,IT部门为什么需要ITSM