Why instancemethod when I can add functions to classes outside class body?
Rim
rimbalaya at yahoo.com
Mon Jul 28 11:05:53 EDT 2003
"Terry Reedy" <tjreedy at udel.edu> wrote in message
> > >>> class A: pass
> ...
> > >>> a1 = A(); a2 = A()
> > >>> a1.f = new.instancemethod(lambda self: "hi", a1, A)
> > >>> a2.f()
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> > AttributeError: A instance has no attribute 'f'
> > >>> a1.f()
> > 'hi'
>
> 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
I don't understand why you say "no automatic access". 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
>>> b=a("Joe")
>>> b.f()
hello
hi
Joe
I obviously don't understand what you are trying to explain to me.
>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
I think someone should write the official definitions for the following
so we all talk the same language:
- function
- method
- bound method/function
- unbound method/function
- class-wide method/function
- class-not-wide method/function
- etc.
> requires the wrapping to avoid having to explicitly pass the instance.
I did not pass the instance and it worked in my example. I'd like to understand
what you are trying to show me.
Thanks,
-Rim
More information about the Python-list
mailing list