问题描述
我刚刚在学习 Python OOP.在某些框架的源代码中,我遇到了 return super(...
并想知道两者之间是否有区别.
class a(object):def foo(self):打印 'a'b类(对象):def foo(self):打印'b'A(a)类:def foo(self):super(A, self).foo()B(b)类:def foo(self):返回 super(B, self).foo()>>>aie = A();蜜蜂 = B()>>>aie.foo();蜜蜂.foo()一种乙
在我看来是一样的.我知道,如果你允许的话,OOP 会变得非常复杂,但在我的学习过程中,我没有足够的资金来提出更复杂的例子.是否存在返回 super
与调用 super
不同的情况?
是的.考虑这样一种情况:超类的 foo
不仅返回打印,还返回了一些东西:
class BaseAdder(object):def add(self, a, b):返回 a + b类 NonReturningAdder(BaseAdder):def add(self, a, b):super(NonReturningAdder, self).add(a, b)类 ReturningAdder(BaseAdder):def add(self, a, b):return super(ReturningAdder, self).add(a, b)
给定两个实例:
>>>a = NonReturningAdder()>>>b = ReturningAdder()当我们在 a
上调用 foo
时,似乎什么也没发生:
然而,当我们在 b
上调用 foo
时,我们得到了预期的结果:
那是因为 NonReturningAdder
和 ReturningAdder
都调用了 BaseAdder
的 foo
,NonReturningAdder
丢弃其返回值,而 ReturningAdder
将其传递.
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.
这篇关于`super(...)` 和 `return super(...)` 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!