首页 > 代码库 > python初始化父类错误
python初始化父类错误
源码如下:
#!/usr/bin/env pythonclass Bird(): def __init__(self): self.hungry = True def eat(self): if self.hungry: print ‘Aaaah...‘ self.hungry = False else: print ‘No, Thanks!‘class SongBird(Bird): def __init__(self): super(SongBird, self).__init__() # Bird.__init__(self) self.sound = ‘Squawk!‘ def sing(self): print self.sound
错误信息如下:
>>> from Bird import Bird, SongBird>>> b = Bird()>>> b.eat()Aaaah...>>> b.eat()No, Thanks!>>> sb = SongBird()Traceback (most recent call last): File "<stdin>", line 1, in <module> File "Bird.py", line 17, in __init__ super(SongBird, self).__init__()TypeError: must be type, not classobj
错误原因:
使用super初始化父类只对父类为新风格(new-style)的生效,对旧风格的不生效。
解决方式1:
#!/usr/bin/env python# 使用new-styleclass Bird(object): def __init__(self): self.hungry = True def eat(self): if self.hungry: print ‘Aaaah...‘ self.hungry = False else: print ‘No, Thanks!‘class SongBird(Bird): def __init__(self): super(SongBird, self).__init__() self.sound = ‘Squawk!‘ def sing(self): print self.sound
解决方法2:
#!/usr/bin/env python__metaclass__ = typeclass Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print ‘Aaaah...‘ self.hungry = False else: print ‘No, Thanks!‘class SongBird(Bird): def __init__(self): super(SongBird, self).__init__() self.sound = ‘Squawk!‘ def sing(self): print self.sound
解决方法3(使用old-style):
#!/usr/bin/env pythonclass Bird(): def __init__(self): self.hungry = True def eat(self): if self.hungry: print ‘Aaaah...‘ self.hungry = False else: print ‘No, Thanks!‘class SongBird(Bird): def __init__(self): # 不使用super进行初始化 Bird.__init__(self) self.sound = ‘Squawk!‘ def sing(self): print self.sound
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。