Domanda

This is sort of an add-on question in reference to the very popular super( ) question. The question was basically "Why should I use super( )" and the answer was "Because you don't have to reference the parent class, which can be nice."

My question is...why in the world is that a good thing? Whatever happened to "Explicit is better than implicit?" Let's say I'm reading some other developer's code and I see:

class Foo(Bar, Baz):
    def my_method(self):
        super(Foo, self).who_knows( ) #nobody knows!

I now have to dig through the docs on Bar and Baz and all of their parent classes all the way up the tree to find out where who_knows( ) is being called from and what it does. I also need a perfect understanding of the Method Resolution Order in order to know which who_knows( ) is actually being called.

Now let's look at the same code without super( ):

class Foo(Bar, Baz):
    def my_method(self):
        Baz.who_knows(self) #ah, Baz knows

Much clearer, no guesswork or understanding of the MRO required.

I'm not raising this question to start an argument or a philosophical discussion. I'm just hoping that someone can show me some very clear examples in which the implicit nature of super( ) is actually desirable because honestly I'm not seeing it.

È stato utile?

Soluzione 2

When you are delegating implementations to other parts of code, being "explicit" about how that code is written defeats the purpose. Knowing exactly what is being called equates to having a dependency on that implementation so that if one piece of code changes the other must change also.

Consider that the problem of ambiguity still exists with the old Baz.who_knows(self) method. If Baz does not override who_knows, then you still don't know which of Baz's superclasses define the actual implementation. So do you change that line in Foo's code to point to the class that actually implements it? But if you then do decide to override it in Baz, you need to update Foo again (as well as all other subclasses).

Altri suggerimenti

For this case specifically, super(Foo, self).who_knows() is not a good thing at all. I would just do self.who_knows().

super() is commonly used when overriding the method with the same name from parent class.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top