Python Learning notes-how to construct

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.