super() fails with error: TypeError “argument 1 must be type, not classobj”

关于Python的面向对象的编程有这样一个例子:

class Bird:
    def __init__(self):
        self.hungry = 1
    def eat(self):
        if self.hungry:
            print 'Aaaah...'
            self.hungry = 0
        else:
            print 'No, thanks!'

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

def test():
    t=SongBird()
    t.sing()
    t.eat()

if __name__ == '__main__':
    test()
这时运行会报错,按照C++的OO特性来了解,SongBird类继承了Bird类的方法,包括魔术方法构造函数,在new出一个Songird类的对象t时,会自动执行父类的构造函数,但是在python中并不是这样,而是的借助super()这个函数来显式调用才会生效,如果没有super那个函数,会报错

加上后,同样会报错,报错信息为:

super() fails with error: TypeError “argument 1 must be type, not classobj”

参考stackoverflow的解决说明:

Your problem is that class B is not declared as a "new-style" class. Change it like so:

class B(object):

and it will work.

super() and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that (object) on any class definition to make sure it is a new-style class.

Old-style classes (also known as "classic" classes) are always of type classobj; new-style classes are of type type. This is why you got the error message you saw:

TypeError: super() argument 1 must be type, not classobj

所以解决方法有两种:

1.在开头显示说明使用new-style classes,在开头加上__metaclass__=type

2.sof上的解决方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值