class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
# super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
super(FooChild,self).__init__()
print ('Child')
def bar(self,message):
super(FooChild, self).bar(message)
print ('Child bar fuction')
print (self.parent)
if __name__ == '__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
结果:
Parent 这是print的结果父类打印
Child 子类打印
到这里已经执行完FooChild()这一步了
HelloWorld from Parent 父类赋值打印
Child bar fuction 子类打印
I'm the parent. 打印self.parent是父类的值
python的函数---super
最新推荐文章于 2025-07-01 14:50:33 发布
本文详细介绍了Python中使用super()函数实现类继承的方法,包括如何在子类中调用父类的初始化方法和成员函数,展示了super()在解决多重继承时带来的便利。
1047

被折叠的 条评论
为什么被折叠?



