If you override the constructor of a class,which always happend in inheritance,you need to call the constructor of the superclass (the class you inherit from) or risk having an object that isn't properly initialized.
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):
self.sound = 'Squawk!'
def sing(self):
print self.sound
>>> sb=SongBird()
>>> sb.eat()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "birds.py", line 6, in eat
if self.hungry:
AttributeError: SongBird instance has no attribute 'hungry'
class SongBird(Bird):
def __init__(self):
Bird.__init__(self)
self.sound = 'Squawk!'
def sing(self):
print self.sound
If you retrieve the method directly from the class (such as in Bird.__init__), there is no instance to which to bind. Therefore, you are free to supply any self you want to. Such a method is called unbound.
By supplying the current instance as the self argument to the unbound method, the songbird gets the full treatment from its superclass’s constructor (which means inserting the subclass instance into the base-class self,so that it has its hungry attribute set).
It is called with the current class and instance as its arguments, and any method you call on the returned object will be fetched from the superclass rather than the current class.
class SongBird(Bird):
def __init__(self):
super(SongBird, self).__init__()
self.sound = 'Squawk!'
def sing(self):
print self.sound
class Bird:
def __init__(self,arguments):
pass
class SongBird(Bird):
def __init__(self):
super(SongBird, self).__init__(arguments)