Python class Four: Inheritance of classes and overriding of parent class methods

Source: Internet
Author: User



Python inherits that subclasses can override various methods of the parent class, including the __init__ method.

If you want to overwrite the __init__ method of the parent class, and you want to refer to the __init__ method of the parent class in the overridden method, such as adding some properties to the __init__ method of the parent class or something else.


You need to display a method that references the parent class, otherwise the parent class's methods are not called directly to.


Like what:


#coding: utf-8# C Inherits P and implements its own __init__ method, that is, to re-implement the __init__ method, but in order to reduce the code redundancy # C in its own __init__ method refers to the __init__ method of P,  This method needs to display the call p, and to pass the self variable to P's # __init__ method class P (object): Def __init__ (self,nm): Self.name = Nmclass C (p): def __init__ (Self,nm,idnum): p.__init__ (self,nm) self.id = IDNUMC1 = C (' John ', one) print C1print c1.name,c1.id


The operating result is:


[Email protected] eg_4]# python2.7 class_inherit_demo_4.py<__main__.c object at 0x7efdf2ff6a90>john 11









Python class Four: Inheritance of classes and overriding of parent class methods

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.