python初始化父類錯誤

源碼以下:python

#!/usr/bin/env python

class 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

 

錯誤信息以下:spa

>>> 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


錯誤緣由:code

使用super初始化父類只對父類爲新風格(new-style)的生效,對舊風格的不生效。blog

 

解決方式1:源碼

#!/usr/bin/env python

# 使用new-style
class 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:it

#!/usr/bin/env python

__metaclass__ = type

class 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):ast

#!/usr/bin/env python

class 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
相關文章
相關標籤/搜索