Python 子类调用父类方法
来源:互联网 发布:淘宝足球装备 编辑:程序博客网 时间:2024/06/05 14:10
Python在继承时,如果子类重写了init()函数,则父类的init()不会被调用,这时如果子类只是想要对父类的init()函数进行简单的扩展的话,是很不方便的。那么有没有比较方便的方法来从子类调用父类呢?
第一种是直接使用父类的类名来直接调用。(Python3.3)
class Parent: def __init__(self): print('This is parent init.') def sleep(self): print("Parent sleeps.")class Child(Parent): def __init__(self): Parent.__init__(self) print('This is child init.') def sleep(self): print("Child sleeps.")c=Child()
第二种是使用形如super(type, obj).methodName(args)调用,第一个参数表示从哪个类开始找其父类(不包括其自身),第二个参数表示类实例(一般使用self),参数args在父类方法的参数只有self时不写。
class Parent: def __init__(self): print('This is parent init.') def sleep(self): print("Parent sleeps.")class Child(Parent): def __init__(self): #Parent.__init__(self) super(Child,self).__init__() print('This is child init.') def sleep(self): print("Child sleeps.")c=Child()
当在类内部使用时,super(type, obj).methodName(args)中的type, obj可以省略不写。
另外,在类外面也可以使用这一函数,比如当子类覆盖了父类的某一方法后,想要通过子类的对象调用父类的这一方法:
class Parent: def __init__(self): print('This is parent init.') def sleep(self): print("Parent sleeps.")class Child(Parent): def __init__(self): #Parent.__init__(self) super().__init__() print('This is child init.') def sleep(self): print("Child sleeps.")c=Child()c.sleep()super(Child,c).sleep()
0 0
- Python 子类调用父类方法
- Python 子类调用父类方法
- python子类调用父类的方法
- Python 子类调用父类的方法
- python子类调用父类的方法
- python子类调用父类的方法
- python子类调用父类的方法
- python子类调用父类的方法
- 4. python 子类调用父类方法
- Python 父类调用子类方法
- Python中子类怎样调用父类方法
- Python学习笔记--子类调用父类方法
- python中子类调用父类构造方法
- Python中子类怎样调用父类方法
- python中子类实例化调用父类方法
- python子类调用父类的方法-super
- python学习笔记:子类怎样调用父类方法
- python子类如何调用父类的__init__方法
- 初探freetype字体库
- C++泛型详解
- 题目1061:成绩排序
- UNIX/Linux-进程控制(实例入门篇)
- 项目范围管理
- Python 子类调用父类方法
- Ubuntu 架設nfs server
- Boost filesystem 之 read files
- Python 表list, 元组tuple, 字典dict
- Redis应用场景
- Android 当listview某项被选中时,改变字体的颜色,采用XML来配置
- 人工神经网络学习笔记_Hopfield网络_递归网络
- Python 集合set
- C语言项目--《工资管理系统》