简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM