Pointing to function from class
Alex Martelli
aleaxit at yahoo.com
Tue Oct 17 06:20:14 EDT 2000
"Adam Clark" <bjrubble at shell16.ba.best.com> wrote in message
news:8sgrd7$2u3c$1 at nntp1.ba.best.com...
> Hi.
>
> I want something like this:
>
> def SomeFunc () :
> # doesn't take self and can be called from outside a class
>
> class Class :
> f = SomeFunc
>
> c = Class()
> c.f()
>
> I can't keep the class from trying to bind the function.
Yep, functions "mutate" into unbound-methods when they are
set as class-properties:
>>> def f():
print "f here"
>>> class X:
pass
>>> X.f=f
>>> X.f
<unbound method X.f>
>>> f
<function f at 00F929AC>
>>>
The 'mutation' is "irreversible" (by normal means...):
>>> f()
f here
>>> X.f()
Traceback (innermost last):
File "<pyshell#35>", line 1, in ?
X.f()
TypeError: unbound method must be called with class instance 1st argument
>>> g=X.f
>>> g
<unbound method X.f>
>>> g()
Traceback (innermost last):
File "<pyshell#38>", line 1, in ?
g()
TypeError: unbound method must be called with class instance 1st argument
>>>
So you want a callable that is not a function. E.g.:
>>> class Callable:
def __init__(self, f):
self.f=f
def __call__(self, *args, **kwds):
return apply(self.f, args, kwds)
>>> X.f=Callable(f)
>>> X.f()
f here
>>>
No mutation here -- the function->unboundmethod mutation only
applies to a *function*, not to a generic callable. Here,
we have an instance (that is callable), so, no mutation.
Alex
More information about the Python-list
mailing list