Reference to self not passed to member function
Scott David Daniels
Scott.Daniels at Acm.Org
Fri May 6 19:22:32 EDT 2005
James Stroud wrote:
> Hello All,
>
> I did this:
>
> py> class bob(object):
> ... def __init__(self,**kwargs):
> ... for fname,func in kwargs.items():
> ... setattr(self, fname, lambda *args : func(*args))
> ...
> py> def doit():
> ... print "wuzzup?"
> ...
> py> abob = bob(doit=doit)
> py>
> py> abob.doit()
> wuzzup?
> Much to my surprise, this works fine.
> 1. What exactly is going on?
This behavior shouldn't surprise you. You stored a function as
an attribute. In fact you could have simply done:
py> class bob(object):
... def __init__(self,**kwargs):
... for fname, function in kwargs.items():
... setattr(self, fname, function)
> 2. How can I get ref to self passed to doit() if I want it to? This:
> abob.doit(abob)
py> import new
py> class carol(object):
... def __init__(self, **kwargs):
... for name, method in kwargs.items():
... setattr(self, name,
... new.instancemethod(method, self, carol))
This should behave as you prefer.
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list