Which class method will be used when calling it?

Pearu Peterson pearu at cens.ioc.ee
Fri Mar 15 10:28:48 EST 2002


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()?

To make my question clearer, I need the following codelet

  if <x.f is A.f>: pass
  else: x.f()

So that if x=b or x=b1, then its method f is called. But if x=a or x=c,
then the pass statement is executed. 

A special solution would be

  <x.f is A.f>  = hasattr(x.__class__,'f')

but it only works if certain conditions are satisfied (x.__class__ is
directly derived from A). It obviously fails in the b1 case.

Are there less restrictive solutions available under Python 2.2?


Thanks,
	Pearu




More information about the Python-list mailing list