Why instancemethod when I can add functions to classes outside class body?

Anders J. Munch andersjm at dancontrol.dk
Fri Jul 25 06:30:58 EDT 2003


"Ben Finney" <bignose-hates-spam at and-benfinney-does-too.id.au> wrote:
> On 25 Jul 2003 07:18:15 +0200, Martin v. Löwis wrote:
> > rimbalaya at yahoo.com (Rim) writes:
> >> So what problem is the new.instancemethod() trying to solve?
> >
> > It has no side effects on the class it is an instancemethod of.
>
> So what side effects (i.e. what problem) is the new.instancemethod()
> trying to solve?

Assigning to the class changes the behaviour of all instances of that
class.  new.instancemethod can be used to add a method to an
individual instance.

>>> 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'


- Anders






More information about the Python-list mailing list