calling class methods as functions

Alex Martelli aleax at aleax.it
Tue Apr 9 05:47:16 EDT 2002


Giorgi Lekishvili wrote:

> Hello!
> 
> I wonder if someone explaines tom how can I overcome the following
> problem in Python2.0 (I have to use this interpreter):

2.0 didn't have class methods : class methods were introduced in 2.2.

What you are calling a class method is an ordinary method.


> suppose, we have 2 classes, B, and C.

Unrelated.  OK.


> in class B we have a method "write"
> 
> in class C we have a method "write"
> 
> def write (self, arg):
>     import B
>     res=B.B.write(self, arg)    #res is a string being either "ok" or
> "failure"
>     del B
>     return res
> 
> 
> The interpreter gives an error, that class isntance must be given as 1st
> argument.
> 
> What's wrong?

B.B.write is an *unbound method* and it carries along the information
that it was extracted from class B, exactly in order to avoid you
accidentally calling it on objects it wasn't meant to be called on.

If you want to extract the method's underlying function, that's
B.B.write.im_func.  It's a very peculiar thing to do -- if write
COULD indeed be called on anything, you should not code it as a
method, within class B, but as a function within module B.  Still,
for whatever peculiar needs you may have, the language lets you
call B.B.write.im_func(self, arg) -- "on your head be it":-).


Alex




More information about the Python-list mailing list