[Tutor] Adding method to class after class initialization

Remco Gerlich scarblac@pino.selwerd.nl
Fri, 17 Nov 2000 08:02:07 +0100

On Fri, Nov 17, 2000 at 12:47:42AM -0600, Stephan Richter wrote:
> Hello everyone,
> here a hard nut to crack:
> Let's say I do the following:
>  >>> def add(self, x, y):
> ...        return x+y
>  >>> class Test:
> ...        pass
>  >>> t = Test()
>  >>> t.add = add
> But if I now call 'a.add(3, 3)' I did not pass enough arguments, since self 
> is not passed automatically. How can I fix that? Is there something like 
> setattr just for a method?

If you define a method in a class, it is a "bound method", meaning that
the self is passed automatically. Setting it as t.add=add means that t.add
is just another variable, where its value happens to be a function.

You can make new codeobjects with the 'new' module. Use new.instancemethod

>>> t.add = new.instancemethod(add, t, Test)

Remco Gerlich