问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/18649348/what-is-the-difference-between-super-and-return-super