#python # Subclasses call a method of a parent class function

Source: Internet
Author: User

The __init__ () function in a subclass of Python overrides the function of the parent class, and in some cases it is necessary to call the parent class function in the subclass.

In the following routines,??? is where the parent class function needs to be called, and the following routines are described in detail.

11#-*-coding:utf-8-*-22classStudent:33def __init__(self,name):44 self.name=name55defPS (self):66Print('I am%s'%self.name)7788classscore (Student):99def __init__(self,name,score):TenTen self.score=score One11???
A12defPS1 (self): -13Print('i\ ' m%s,%s'%(Self.name,self.score)) -14 theScore ('Bob',' About'). PS () -Score ('Bob',' About'). PS1 ()

In Python3.5, the following methods are available for accessing data.

The first is direct method. Called directly with the parent class name, such as Parent_class.parent_attribute (self), which corresponds to a routine statement:

Student. __init__ (Self,name)

The second is through the super function, shaped like super (Child_class, Child_object). Parent_attribute (ARG). The first parameter represents the beginning of the call to the parent class, and the second parameter represents the class instance (usually self), and the parameter args does not have to be written when the parameter of the parent class method is self-only. In addition, when used within the class, Child_class, Child_object can also be omitted. corresponding routines:

Super (Score,self). __init__ (name)

Or:

Super (). __init__ (name)

The super function can also be used outside the class, but there are Child_class, child_object two parameters.

#python # Subclasses call a method of a parent class function

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.