Python学习笔记(一)——super()函数

super()函数是用来调用父类的方法。
其用法分为两步:
1、找到父类;
2、调用父类对应的方法。

实例1:

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):
#继承自父类FooParent
    def __init__(self):
        super(FooChild,self).__init__()   
         # super(FooChild,self):首先找到 FooChild 的父类(就是类 FooParent)
         # 然后调用父类 FooParent 的方法
        print ('Child')
        
    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction')
        print (self.parent)
 
 fooChild = FooChild()
 fooChild.bar('HelloWorld')

执行结果为:

Parent
Child
HelloWorld from Parent
Child bar fuction
I\'m the parent

实例2:

class A:
     def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super().add(x)
        #相当于super(B,self).add(x),不写的时侯默认是自己
b = B()
b.add(2)  # 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值