Why instancemethod when I can add functions to classes outside class body?
Terry Reedy
tjreedy at udel.edu
Mon Jul 28 11:30:32 EDT 2003
"Rim" <rimbalaya at yahoo.com> wrote in message
news:6f03c4a5.0307280705.6a4ab103 at posting.google.com...
> "Terry Reedy" <tjreedy at udel.edu> wrote in message
> > So to answer the OP's question, the problem solved is that
directly
> > assigning a function as an instance attribute binds the function
as a
> > function, which means no *automatic* access to the instance and
its
> > other attributes.
> I don't understand why you say "no automatic access".
Re-read the sentence again. The key point is 'assign ... as instance
attribute'.
> If you examine
> the following, I have access to the attributes defined in the class,
> without doing anything special:
>
> >>> class a:
> ... def __init__(self,name):
> ... self.msg = "hi"
> ... self.name = name
> ...
> >>> def f(self):
> ... print "hello"
> ... print self.msg
> ... print self.name
> ...
> >>> a.f = f
a is the class, not an instance, making the new class attribute f a
method just as if it has been part of the class statement.
> >>> b=a("Joe")
> >>> b.f()
> hello
> hi
> Joe
Try b.f = f instead and then call b.f() and b.f(b).
Now try b.f = new.instancemethod(f) and then call b.f() and b.f(b).
The results should answer your questions.
Terry J. Reedy
> >So to answer the OP's question, the problem solved is that directly
> >assigning a function as an instance attribute binds the function as
a
> >function, which means no *automatic* access to the instance and its
> >other attributes. If such access is needed, the instance must be
> >passed explicitly, as in
> >a1.f = lambda self: repr(self)
> >a1.f(a1)
> >
> >Instancemethod adds the option of wrapping instance-specific
functions
> >as bound methods getting the instance as an automatic first (self)
> >paramater, just like with class-wide methods. In the 'hi' example
More information about the Python-list
mailing list