'self' disappearing
Steven Taschuk
staschuk at telusplanet.net
Sat Jul 5 17:44:02 EDT 2003
Quoth Daniel Nouri:
> The idea of my simple piece of code is to start from a given module and
> wrap all functions and methods in that module and submodules. FunWrapper is
> the class that I use for wrapping.
[...]
> It appears that 'instance.method()' is not the same as
> 'klass.method(instance)' in this case. But why? And how do I deal with
> that?
Your function wrapper implements only the __call__ protocol; you
also need to handle the descriptor protocol, which is used to
implement the bound/unbound method business. For example:
class FunWrapper(object):
def __init__(self, fun):
self.fun = fun
def __call__(self, *args, **kwds):
print 'Calling', self.fun.__name__
self.fun(*args, **kwds)
def __get__(self, *args):
print 'Getting', self.fun.__name__
return FunWrapper(self.fun.__get__(*args))
class Foo(object):
def bar(*args):
print 'called with args', args
bar = FunWrapper(bar)
foo = Foo()
foo.bar('a', 'b', 'c')
You might find Raymond Hettinger's writeup of descriptors useful
to understand what's going on here:
<http://users.rcn.com/python/download/Descriptor.htm>
--
Steven Taschuk staschuk at telusplanet.net
"I may be wrong but I'm positive." -- _Friday_, Robert A. Heinlein
More information about the Python-list
mailing list