python super()函数的基本使用
作者:新码农 时间:2022-01-11 05:24:40
super主要来调用父类方法来显示调用父类,在子类中,一般会定义与父类相同的属性(数据属性,方法),从而来实现子类特有的行为。也就是说,子类会继承父类的所有的属性和方法,子类也可以覆盖父类同名的属性和方法。
class Parent(object):
Value = "Hi, Parent value"
def fun(self):
print("This is from Parent")
# 定义子类,继承父类
class Child(Parent):
Value = "Hi, Child value"
def ffun(self):
print("This is from Child")
c = Child()
c.fun()
c.ffun()
print(Child.Value)
# 输出结果
# This is from Parent
# This is from Child
# Hi, Child value
但是,有时候可能需要在子类中访问父类的一些属性,可以通过父类名直接访问父类的属性,当调用父类的方法是,需要将”self”显示的传递进去的方式。
class Parent(object):
Value = "Hi, Parent value"
def fun(self):
print("This is from Parent")
class Child(Parent):
Value = "Hi, Child value"
def fun(self):
print("This is from Child")
# 调用父类Parent的fun函数方法
Parent.fun(self)
c = Child()
c.fun()
# 输出结果
# This is from Child
# This is from Parent
# 实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法
这种方式有一个不好的地方就是,需要经父类名硬编码到子类中,为了解决这个问题,可以使用Python中的super关键字。
class Parent(object):
Value = "Hi, Parent value"
def fun(self):
print("This is from Parent")
class Child(Parent):
Value = "Hi, Child value"
def fun(self):
print("This is from Child")
# Parent.fun(self)
# 相当于用super的方法与上一调用父类的语句置换
super(Child, self).fun()
c = Child()
c.fun()
# 输出结果
# This is from Child
# This is from Parent
# 实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法
来源:https://www.addcoder.com/blog/article_detail/grzc0p7w/
标签:python,super(),函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
css学习笔记: css新闻列表的特殊做法
2009-07-19 14:25:00
![](https://img.aspxhome.com/file/UploadPic/20097/19/11e89610908g215-71s.jpg)
Python队列RabbitMQ 使用方法实例记录
2021-01-30 22:38:26
![](https://img.aspxhome.com/file/2023/3/83753_0s.png)
PHP实现数组根据某个字段进行水平合并,横向合并案例分析
2023-10-04 04:55:53
解决SQL Server的“此数据库没有有效所有者”问题
2011-12-14 18:29:35
运行tensorflow python程序,限制对GPU和CPU的占用操作
2022-07-03 02:49:26
扫盲大讲堂:SQL查询结果集对注入的影响及利用
2009-09-05 09:49:00
python 用matplotlib绘制折线图详情
2022-03-23 16:38:19
![](https://img.aspxhome.com/file/2023/3/92003_0s.png)
在ASP中使用SQL语句之4:联合语句
2007-08-11 12:34:00
修炼设计能力的土办法
2008-07-16 10:34:00
Google Chrome CSS选择器速度测试比较
2008-10-06 13:24:00
![](https://img.aspxhome.com/file/UploadPic/200810/6/2008106174242741s.png)
Python实现按照指定要求逆序输出一个数字的方法
2023-12-21 23:37:46
![](https://img.aspxhome.com/file/2023/3/92523_0s.png)
解决tensorflow添加ptb库的问题
2022-05-28 07:44:02
SQL Server 2005:数据类型最大值
2009-06-04 09:55:00
python并发编程 Process对象的其他属性方法join方法详解
2022-03-07 04:29:54
使用keras时input_shape的维度表示问题说明
2023-05-10 02:52:25
![](https://img.aspxhome.com/file/2023/3/92193_0s.jpg)
Jupyter notebook运行Spark+Scala教程
2023-04-18 08:48:56
![](https://img.aspxhome.com/file/2023/4/80434_0s.jpg)
Python函数参数定义及传递方式解析
2021-10-19 21:28:25
pyqt5实现俄罗斯方块游戏
2023-07-21 11:02:32
![](https://img.aspxhome.com/file/2023/8/84118_0s.png)
Python图像处理之图像的灰度线性变换
2021-12-16 22:30:58
![](https://img.aspxhome.com/file/2023/7/65977_0s.png)
如何利用Python开发一个简单的猜数字游戏
2022-05-21 20:38:08
![](https://img.aspxhome.com/file/2023/6/86316_0s.jpg)