Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between super() and super (className,self) in Python [duplicate]

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?

like image 805
Taohidul Islam Avatar asked Jan 12 '19 18:01

Taohidul Islam


People also ask

What is the difference between self and super in Python?

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.

What is super class self in Python?

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.

What is super () __ Init__ in Python?

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.

What is super () method in Python?

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.


1 Answers

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

like image 90
FrenchMasterSword Avatar answered Sep 28 '22 12:09

FrenchMasterSword