Noob Saibot
Noob Saibot

Reputation: 4759

What is the difference between `super(...)` and `return super(...)`?

I'm just now learning about python OOP. In some framework's source code, i came across return super(... and wondered if there was a difference between the two.

class a(object):
    def foo(self):
        print 'a'

class b(object):
    def foo(self):
        print 'b'

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

class B(b):
    def foo(self):
        return super(B, self).foo()

>>> aie = A(); bee = B()
>>> aie.foo(); bee.foo()
a
b

Looks the same to me. I know that OOP can get pretty complicated if you let it, but i don't have the wherewithal to come up with a more complex example at this point in my learning. Is there a situation where returning super would differ from calling super?

Upvotes: 17

Views: 16882

Answers (1)

icktoofay
icktoofay

Reputation: 129059

Yes. Consider the case where rather than just printing, the superclass's foo returned something:

class BaseAdder(object):
    def add(self, a, b):
        return a + b

class NonReturningAdder(BaseAdder):
    def add(self, a, b):
        super(NonReturningAdder, self).add(a, b)

class ReturningAdder(BaseAdder):
    def add(self, a, b):
        return super(ReturningAdder, self).add(a, b)

Given two instances:

>>> a = NonReturningAdder()
>>> b = ReturningAdder()

When we call foo on a, seemingly nothing happens:

>>> a.add(3, 5)

When we call foo on b, however, we get the expected result:

>>> b.add(3, 5)
8

That's because while both NonReturningAdder and ReturningAdder call BaseAdder's foo, NonReturningAdder discards its return value, whereas ReturningAdder passes it on.

Upvotes: 27

Related Questions