Adding method to object
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Wed Dec 3 07:02:37 EST 2003
On Wed, 03 Dec 2003 10:44:12 +0100, "Thomas Guettler"
<guettli at thomas-guettler.de> wrote:
>Hi!
>
>How can I add a method to an object.
>This code does not work:
>
>class Foo:
> def __init__(self):
> self.counter=0
>
>f=Foo()
>
>def incr(self):
> self.counter+=1
>
>f.incr=incr
>
>f.incr()
>
>===> python extend.py
>Traceback (most recent call last):
> File "extend.py", line 12, in ?
> f.incr()
>TypeError: incr() takes exactly 1 argument (0 given)
You have to call it like
f.incr(f)
If you want to leave out the f as arg (call it like an instance
method) then
>>> import new
>>> help(new.instancemethod)
Help on class instancemethod in module __builtin__:
class instancemethod(object)
| instancemethod(function, instance, class)
|
| Create an instance method object.
|
...
And
new.instancemethod(incr, f, f.__class__)
Should do the trick.
With my best regards,
G. Rodrigues
More information about the Python-list
mailing list