Which class method will be used when calling it?

Jeff Shannon jeff at ccvcorp.com
Fri Mar 15 19:24:07 EST 2002


Pearu Peterson wrote:

> Hi,
>
> Let's define classes
>
> class A:
>   def f(self): pass         # define default method f
>
> class B(A):
>   def f(self): pass         # define specific method f
>
> class B1(B): pass           # specific B.f is available
>
> class C(A): pass            # no specific method f, default is available
>
> and instances:
>
> a = A()
> b = B()
> b1 = B1()
> c = C()
>
> Given one of these instances, how to tell which method will be called,
> the default f or a specific f, if calling <instance>.f()?

In attempting to find the method to use, Python searches the most derived
class first, then the most recent ancestor, then any ancestors of that,
etc...

Thus, you will get the following calls:

a.f() == A.f(a)
b.f() == B.f(b)
b1.f() == B.f(b1)
c.f() == A.f(c)

The only complications to watch for, is if you have a "diamond" inheritance
pattern -- in other words, if you were to define a class D like so:

class D(B, C):
    pass

d = D()

Now it becomes a bit more difficult to figure out which version of f() is
called.  In Python 2.1 and earlier, the base classes are searched
depth-first, so that the call would resolve to B.f(), but if class D were
declared as D(C, B) [note reverse order of ancestors], then d.f() would
resolve to A.f() (since C has no f(), but C's parent A does).  Python 2.2
changed this, so that (in essence) a breadth-first search is done; under
2.2, d.f() should resolve to B.f() regardless of the order that the parents
were listed when D was declared.

(At least, I *think* I'm remembering this correctly.... ;) )

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list