Python calls the parent class method

Source: Internet
Author: User

This article and everyone to share is mainly in Python development , call the parent class two methods similarities and differences, I hope to learn from you and use the Python language is helpful.

There are two ways to call the parent class in Python: super (Child, Self). Method (args) and Parent.method ( Self, args) . I used one of these to report the following error:


I can't find them . Classobj . When I change the call to super (B, self), F (name) works correctly and the result is correct.

parsing errors

because the base class does not inherit Object , in python , one can be created like this:

class A:

Pass

You can also create this:

class A(object):

Pass

The difference between the two is:

This is the old class . ( former ) and new types ( latter ) the difference.

Python3 has removed the old type, meaning that it has implicitly inherited the object , so thePython3 does not write the inheritance Object there's no difference.

Two different types of calls

What is the difference between parent.__init__ (self) and super (Child, self). __init__ () ?

Super understands the parent class as well,Python actually refers to the next class in MRO!

Super actually did this , look at the answer :

def Super(CLS, inst):

MRO = Inst.__class__.mro () # Always the most derived class

return mro[mro.index (CLS) + 1]

MRO Full name Method Resolutionorder, which represents the order in which classes inherit.

Super is used to solve multiple inheritance problems , assuming B C D is directly inheriting class A

class E(B, C, D):

def __init__(self):

# code ...

if the Class E constructor uses super (E, self). __init__ () , The Class A constructor is executed once, and in another way,a The constructor of the class is executed multiple times.

in MRO , the base class always appears after the derived class, and if there are multiple base classes, the relative order of the base classes remains unchanged.

Source: Habitat later than one mound


Python calls the parent class method

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.