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.