the constructors in python are shaped like def __init__ (self), For example
Class Bird:def __init__ (self): Self.hungry=true def Eat (self): if Self.hungry:print ' Ahhhh ' Self.hungry=false else:print ' no,thx ' Instantiate class Bird Object B:b=bir D () B.eat () b.eat () ahhhhno,thx
Suppose now that Bird has a subclass songbird () that inherits the methods and properties of bird (),
Class Songbird (Bird): def __init__ (self): self.sound= ' Ohlaohaloha ' Def Sing (self): print SELF.SOUNDSB =songbird () sb.eat () sb.eat ()
After the call we see the system error, because Songbird's construction method does not have any code about hungry.
Attributeerror:songbird instance has no attribute ' hungry '
Attempting to add a method eat () in a superclass to a subclass Songbird constructor also gets the same error because the Eat () method contains a hungry variable.
So how do you call the constructor of a superclass in a subclass to initialize it so that the subclass instance has a superclass instance? Available in two ways:
1. Call the unbound superclass construction method:
Class Songbird (Bird): def __init__ (self): bird.__init__ (self) self.sound= ' Ohlaohaloha ' Def Sing (sel f): Print Self.sound
When you add a row of bird.__init__ (self) to a subclass, the instantiated object of the subclass can use all implementations of the superclass's construction method.
Sb=songbird () sb.eat () sb.eat () ahhhhno,thx
2. Use the Super method to invoke the method in the superclass, which refers to the __init__ constructor method.
Class Songbird (Bird): def __init__ (self): Super (Songbird,self). __init__ () self.sound= ' Ohlaohaloha ' def sing (self): print Self.sound
This must be added before use
From _pyio import __metaclass____metaclass__=type
Python Learning notes-how to construct