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上的解决方法

你可能感兴趣的:(Python)