python中super介绍

 
       Python中的 super() 方法设计目的是用来解决多重继承时父类的查找问题,一般我们在子类中需要调用父类的方法时才会这么用。

       super(type[, object-or-type])

  • 参数
    – type: 类。
    – object-or-type: 类,一般是 self

 

示例

 
Eg1.

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):    # FooChild是FooParent的子类
    def __init__(self):
        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')

Out:
              在这里插入图片描述
解析:

fooChild = FooChild():先执行FooChild.__init__()来初始化,然后super(FooChild,self). __init__ ()则是调用FooParent.__init__(),输出Parent,初始化下一句输出Child;

fooChild.bar('HelloWorld'):执行FooChild.bar(),其中第一句super(FooChild, self).bar(message)则又是调用FooParent.bar(),输出HelloWorld from Parent


Eg2.

class C(A):
 	def m(self):
  		print('C')
  		super().m()     #调用C的父类A的m()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值