10

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?

Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
  • 2
    No difference - syntax sugar. – wim Jan 12 '19 at 18:46
  • @wim: well, yes, there very much is a difference, see [Why is Python 3.x's super() magic?](//stackoverflow.com/q/19608134). **Usually** it doesn't matter, but `super(B, self)` looks up `B` *late*. – Martijn Pieters Jan 12 '19 at 18:50
  • Also related: https://www.python.org/dev/peps/pep-3135/ and [Why does Python 2's \`super\` require explicit class and self arguments?](//stackoverflow.com/q/36929210) – Martijn Pieters Jan 12 '19 at 18:54
  • I'm aware, but the intricacies of the implementation are not relevant to this question. – wim Jan 12 '19 at 19:08

1 Answers1

14

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