Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?
Brian Victor
homeusenet4 at brianhv.org
Sat Jul 31 09:29:25 EDT 2010
Steven D'Aprano wrote:
> On Sat, 31 Jul 2010 14:25:39 +1200, Gregory Ewing wrote:
>
>> Steven D'Aprano wrote:
>>
>>> A
>>> / \
>>> C B
>>> \ /
>>> D
>>> / \
>>> E F
>>>
>>> Yes, a super call might jog left from C to B, but only when being
>>> called from one of the lower classes D-F. That's still an upwards call
>>> relative to the originator, not sidewards.
>>
>> But it's not an upward call relative to the class mentioned in the
>> super() call, which is why I say it's misleading.
>
> Which class would that be?
>
> I think I'm going to need an example that demonstrates what you mean,
> because I can't make heads or tails of it. Are you suggesting that a call
> to super(C, self).method() from within C might call B.method(self)?
Yes, it would.
class A(object):
def test_mro(self):
print "In A"
class B(A):
def test_mro(self):
print "In B"
super(B, self).test_mro()
raise Exception()
class C(A):
def test_mro(self):
print "In C"
super(C, self).test_mro()
class D(C, B):
def test_mro(self):
print "In D"
super(D, self).test_mro()
D().test_mro()
Notice the exception being raised in B. This results in the following traceback:
Traceback (most recent call last):
File "mro.py", line 21, in <module>
D().test_mro()
File "mro.py", line 19, in test_mro
super(D, self).test_mro()
File "mro.py", line 14, in test_mro
super(C, self).test_mro()
File "mro.py", line 9, in test_mro
raise Exception()
Exception
Since the idea of super() as I understand it is to make sure every class
in an object's hierarchy gets its method called, there's really no way
to implement super() in a way that didn't involve a non-superclass being
called by some class's super() call.
--
Brian
More information about the Python-list
mailing list