Python super函数的用法

使用方法

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

例子

在继承里如果不使用super会出现如下的错误

class Bird:
    def __init__(self):
          self.hungry = True
    def eat(self):
          if self.hungry:
               print 'Ahahahah'
          else:
               print 'No thanks!'

class SongBird(Bird):
     def __init__(self):
          self.sound = 'Squawk'
     def sing(self):
          print self.song()

sb = SongBird()
sb.sing()    # 能正常输出
sb.eat()     # 报错,因为 songgird 中没有 hungry 特性

因此可以有两种解决方法

绑定参数

class SongBird(Bird):
     def __init__(self):
          Bird.__init__(self)
          self.sound = 'Squawk'
     def sing(self):
          print self.song()

super

class SongBird(Bird):
     def __init__(self):
          super.__init__()
          self.sound = 'Squawk'
     def sing(self):
          print self.song()

它会按照mro顺序查找 ,直到找到要找的为止

菱形继承例子

class A(object):
    def __init__(self):
        print("enter A")
        print(self)  # this will print <__main__.D object at 0x...>
        print("leave A")
class B(A):
    def __init__(self):
        print("enter B")
        print(self)  # this will print <__main__.D object at 0x...>
        super(B, self).__init__()
        print("leave B")
class C(A):
    def __init__(self):
        print("enter C")
        print(self)  # this will print <__main__.D object at 0x...>
        super(C, self).__init__()
        print("leave C")
class D(B, C):
    pass
d = D()

运行结果
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值