The Python implementation subclass calls the parent class method, and the python implementation class calls

Source: Internet
Author: User
Tags one more line

The Python implementation subclass calls the parent class method, and the python implementation class calls

This example describes how to implement a subclass of Python to call the parent class. Share it with you for your reference. The specific implementation method is as follows:

Python is similar to other object-oriented languages. Each class can have one or more parent classes that inherit attributes and methods from the parent class. If a method is called in a subclass instance or an attribute is accessed in the subclass instance, but this method or attribute does not exist in the subclass, then it will automatically go to its parent class for search.

After inheriting the parent class, you can call the parent class method and access the attributes of the parent class. To complete the integration process, the subclass must call the constructor.

The subclass does not explicitly call the constructor of the parent class. However, if the parent class constructor initializes some attributes, a problem may occur.
If both the subclass and the parent class have constructors, The subclass actually overrides the constructor of the parent class. If the parent class constructor is not explicitly called, the constructor of the parent class will not be executed, this causes the subclass instance to access the initial variables in the parent class initialization method.

Let's take a look at the following example:
Copy codeThe Code is as follows: class:
Def _ init _ (self ):
Self. namea = "aaa"
Def funca (self ):
Print "function a: % s" % self. namea
Class B ():
Def _ init _ (self ):
Self. nameb = "bbb"
Def funcb (self ):
Print "function B: % s" % self. nameb
B = B ()
Print B. nameb
B. funcb ()
B. funca ()
Running result:
Copy codeThe Code is as follows: bbb

Function B: bbb
Traceback (most recent call last ):
File "D: workbenchpythonMyPythonProjectteststudyoverwrite_method.py", line 19, in <module>
Print B. funca ()
File "D: workbenchpythonMyPythonProjectteststudyoverwrite_method.py", line 6, in funca
Print "function a: % s" % self. namea
AttributeError: B instance has no attribute 'namea'
In the subclass, the constructor is overwritten, but the new constructor does not have any code to initialize the namea attribute of the parent class. To achieve the expected effect, the constructor of the Child class must call the constructor of its parent class for basic initialization. There are two ways to achieve this purpose: Call the unbound version of The superclass constructor, or use the super function.

Method 1: Call the unbound superclass Constructor

Modify the code and add one more line:
Copy codeThe Code is as follows: class:
Def _ init _ (self ):
Self. namea = "aaa"
Def funca (self ):
Print "function a: % s" % self. namea
Class B ():
Def _ init _ (self ):
# This line solves the problem
A. _ init _ (self)
Self. nameb = "bbb"
Def funcb (self ):
Print "function B: % s" % self. nameb
B = B ()
Print B. nameb
B. funcb ()
B. funca ()
This problem is solved by using the parent class name to call its constructor.

This method is called to call the unbound constructor of the parent class. When an instance method is called, the self parameter of the method is automatically bound to the instance (called the binding method ). However, if you directly call the class method (such as A. _ init), no instance will be bound. In this way, you can freely provide the required self parameter. This method is called the unbound method that is not bound.
By providing the current instance as the self parameter to the unbound method, Class B can use all the implementations of its parent class constructor, so that the namea variable is set.

Method 2: Use the super Function

To modify the code, add two lines to the original code:

Copy codeThe Code is as follows: # The parent class must inherit the object.
Class A (object ):
Def _ init _ (self ):
Self. namea = "aaa"
Def funca (self ):
Print "function a: % s" % self. namea
Class B ():
Def _ init _ (self ):
# This line solves the problem
Super (B, self). _ init __()
Self. nameb = "bbb"
Def funcb (self ):
Print "function B: % s" % self. nameb
B = B ()
Print B. nameb
B. funcb ()
B. funca ()
The above comments are newly added code. In the first sentence, let Class A inherit from the object class to use the super function, because this is A feature supported by python's "New Class. The current lei and object can be used as parameters of the super function. Any method that calls the object returned by the function calls the superclass method, rather than the method of the current class.

The super function will return a super object, which is responsible for method parsing. During the parsing process, it will automatically find all parent classes and parent classes of the parent class.

Method 1 is more intuitive, and method 2 can initialize all superclasses at a time

The super function is more intuitive than calling the unbinding method directly in the super tired state, but the biggest difference is that if the subclass inherits multiple parent classes, it only needs to use the super function once. However, if this requirement is not met, use A. _ init _ (self) to make it more intuitive.

I hope this article will help you with Python programming.

Related Article

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.