Re: How to do class "up-call"?

Guido.van.Rossum@cwi.nl
Wed, 14 Sep 1994 09:23:00 +0200

> You can also go uplevel dynamically -
> instance.__class__ is the class
> instance.__class__.__bases__ is the tuple of that classes super-classes.
>
> >>> x.__class__
> <class c at 200680e8>
> >>> x.__class__.__bases__
> (<class p at 20068128>,)
> >>> x.__class__.__bases__[0].m
> <unbound method p.m>
> >>>
>
>
> But this can be tricky, Guido doesn't recommend it, and there's
> probably very few cases where you need to do it ( i.e. not explicitly
> name the parent/super class. )

Let me explain once more *why* this is dangerous.

Supose you have coded classes B (a base class) and C (a class derived
from B) and in C you call a method of B using __class__.__bases__:

class B:
def meth(self):
print "B.meth"

class C(B):
def meth(self): # override B.meth
print "C.meth"
self.__class__.__bases__[0].meth(self)

If you create a C instance and call its meth() you get the output you
expect:

>>> x = C()
>>> x.meth()
C.meth
B.meth
>>>

Now let's suppose we have a need for a derived class, D, and we don't
need to override meth in D. This could even happen in another module
by another programmer.

class D(C):
def other(self):
print "D.other"

Now if we create a D instance and call its meth(), what do you think
will happen?

>>> x = D()
>>> x.meth()
C.meth
C.meth
C.meth