0

I have a simple question regarding the programming style/convention in python when it comes to superclasses, and calling their methods.

Lets assume I have

class A():
  def a(self):
    print "a"

and I have another class, class B. Is it better to do :-

class B(A):
  pass

vs

class B(A):
  def a(self):
    super(B,self).a()

I eventually want to do : b = B(); b.a() Is there any difference in the two, except for readability?

The Nomadic Coder
  • 580
  • 1
  • 4
  • 16
  • This is a duplicated question. please refer to [https://stackoverflow.com/questions/222877/what-does-super-do-in-python](https://stackoverflow.com/questions/222877/what-does-super-do-in-python) – Wong Siwei Aug 30 '18 at 09:39
  • @WongSiwei I don't ask what super does. I ask when I should use it. What are the scenarios in which super *should* be used and what are the scenarios that I can skip out on it. – The Nomadic Coder Aug 31 '18 at 12:31

2 Answers2

1

You use super when an overriding method should do something in addition to what its base class's method is doing.

For example, if you have class Point and class Circle(Point) and want to implement def move, circles can just reuse point's method they inherit - since moving a circle is precisely moving the circle's centre point.

But if you have class Monster and class Dragon(Monster)... you might want to scorch the land when a dragon walks past, that other monsters would not do. So you'd say that dragon movement is same as normal movement, with some fire added:

class Dragon(Monster):
    def move(self, destination):
        super(Monster, self).move(destination)
        destination.add_some_fire()
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

If you aren't changing or extending the functionality of the parent method, then there's no reason to even define it - let alone override it. If you don't define it, then the parent method will be used.

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22