3

There is obviously a reason for this but I am not experienced enough to recognise it.

This is the example given in the Python docs:

class C(B):
    def method(self, arg):
        super(C, self).method(arg) # Why do we have to mention 'C' again?

Is there not a way of 'knowing' the type from within the instance method that doesn't rely on duplicating the name of the class 'C'? Seems like the example could lead to a situation where the class name is updated but the type parameter in the super function call becomes stale?

HorseloverFat
  • 3,290
  • 5
  • 22
  • 32

2 Answers2

2

On the one hand, DRY is more about large sections of code being duplicated; on the other hand, yes, the class name in super() calls can become stale (it's happened to me).

In Python 3, super() has been revamped to not require the class name, so long as the function is defined inside the class -- so not a problem unless you are monkey-patching.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
1

The same way self is called manually in python super is a simple function, I mean, python functions doesn't know the execution context. This behaviour is practical for monkey patching for example.

For example, I took your C class from pypi and you update it every month as it's a useful class. I want to modify it's method behaviour so it'll update the comportment of other of my requirements using your C class:

from utils import do_magic
from a import C

def method(self, arg):
    super(C, self).method(arg)
    do_magic(self)

C.method = method
christophe31
  • 6,359
  • 4
  • 34
  • 46