Introduction to the super () method in Python

Source: Internet
Author: User
This article mainly introduces the use of the super () method in Python, which is the basic knowledge in getting started with Python. If you need it, you can refer to the subclasses to access the attributes of the parent class with the same name, I don't want to directly reference the name of the parent class, because it may be time to modify it, so it is better to keep only one copy of the data. In fact, there is a better reason not to directly reference the name of the parent class,
At this time, super () will be available --

class A: def m(self):  print('A')class B(A): def m(self):  print('B')  super().m()B().m()

Of course, super () in Python 2 must be a parameter, so you have to write it like this:

class B(A): def m(self):  print('B')  super(B, self).m()

Example of super in single inheritance:

class Foo():  def __init__(self, frob, frotz)    self.frobnicate = frob    self.frotz = frotzclass Bar(Foo):  def __init__(self, frob, frizzle)    super().__init__(frob, 34)    self.frazzle = frizzle

This example is applicable to python 3.x. if you want to use python 3.x, you need to make slight adjustments. The following code example:

class Foo(object):   def __init__(self, frob, frotz):     self.frobnicate = frob     self.frotz = frotz class Bar(Foo):   def __init__(self, frob, frizzle):     super(Bar,self).__init__(frob,34)     self.frazzle = frizzle new = Bar("hello","world") print new.frobnicate print new.frazzle print new.frotz 

You need to mention your own name. This name is also dynamically searched. In this case, replacing the class in the third-party library will cause problems.

'Super () 'solves the problem of accessing methods in the parent class.

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.