I have code snipped like :
class A:
def test(self):
return 'A'
class B(A):
def test(self):
return 'B->' + super(B, self).test()
print(B().test())
Output : B->A
If I write something like this then I'm getting the same output :
class A:
def test(self):
return 'A'
class B(A):
def test(self):
return 'B->' + super().test() # change to super()
print(B().test())
In both cases I'm getting the same output. Then, I want to know what's the difference between this two types of calling of super
? What are the pros and cons of using either of them?
self, which is mostly used as the first parameter of instance methods of classes, always represents the calling object/instance of the class. super() refers to object of parent class.
The Python super() method lets you access methods from a parent class from within a child class. This helps reduce repetition in your code. super() does not accept any arguments. One core feature of object-oriented programming languages like Python is inheritance.
When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
In Python 2, only the super(className,self)
syntax was possible. Since It was the most used version, as of Python 3
providing no arguments will act the same.
There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With