Proper use of super in Python - should I explicitly refer to the class name?

class Foo(object):
    def whee(self):
        return 77

class Bar(Foo):
    def whee(self):
        return super(Bar, self).whee() + 1

class Baz(Foo):
    def whee(self):
        return super(self.__class__, self).whee() + 1

Both Barand Bazreturn the same result for whee(). I use the syntax in Bar. Is there a reason I shouldn't use the syntax in Baz?

+4
source share
1 answer

Is there some reason why I shouldn't use the syntax in Baz?

Yes, there is a reason you should not use this syntax. If you subclass out Baz, the call super()will return to Baz.whee()and you will be stuck in an infinite loop. This also applies to the syntax super(type(self), self).whee().

(Well, in fact, you will cross out the limit of recursion and error. But in any case, this is a problem.)

+7
source

Source: https://habr.com/ru/post/1687663/


All Articles