Execution of constructor during python class inheritance

Source: Internet
Author: User

If the subclass defines its own _ init _ constructor, when the Instance Object of the subclass is created, the subclass will only execute its own _ init _ method function, if the subclass does not define its own constructor, it will find the constructor of the parent class along the search tree to execute the constructor in the parent class.
For example, if a subclass defines its own constructor, if the constructor of the subclass does not actively call the constructor of the parent class, the instance variable of the parent class does not appear when the subclass instance object is just created.

Class aa: def _ init _ (self): self. x = 10 self. y = 12 def hello (self, x): return x + 1 class bb (aa): def _ init _ (self): aa. _ init _ (self) # If this row is canceled, print B below. x and B. y will report an error, not defined # calling the constructor self of the parent class through the class name. z = 14 a = aa () print. x,. yb = bb () print B. x, B. y


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.