4
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 Bar and Baz return the same result for whee(). I'm used to the syntax in Bar. Is there any reason I shouldn't use the syntax in Baz?

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • 2
    Never pass `self.__class__` to `super`. If it was that simple, `super` never would have required that argument in the first place. – user2357112 Oct 17 '17 at 17:27

1 Answers1

6

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

Yes, there is a reason you shouldn't use that syntax. If you subclass from Baz, the super() call will resolve back to Baz.whee() and you'll get stuck in an infinite loop. This also applies to the syntax super(type(self), self).whee().

(Well, actually you will blow the recursion limit and error out. But either way it's a problem.)

Kevin
  • 28,963
  • 9
  • 62
  • 81
  • Oh. oops, that makes sense. – Jason S Oct 17 '17 at 17:28
  • 1
    ...so I guess that means class methods don't have any way of accessing the class they're declared in, unless you explicitly reference that class? – Jason S Oct 17 '17 at 17:29
  • 3
    @JasonS: Yes, that's why Python 3 had to add a "secret" `__class__` local variable holding that info. It's how the zero-args `super()` works. – Kevin Oct 17 '17 at 17:30
  • It's actually possible to access the `__class__` variable explicitly on Python 3 (and it's even documented), but it's not really encouraged, and people will get confused. – user2357112 Oct 17 '17 at 17:37