Adding method to object

Peter Otten __peter__ at web.de
Wed Dec 3 07:28:03 EST 2003


Thomas Guettler wrote:

> How can I add a method to an object.

self is not passed automatically, if you call an instance attribute.
You can provide a default value instead:

>>> class Foo:
...     def __init__(self):
...             self.counter = 0
...
>>> f = Foo()
>>> def incr(self=f):
...     self.counter += 1
...
>>> f.incr = incr
>>> f.incr()
>>> f.counter
1
>>>

If you have more than one instance with the same incr() method, you can wrap
it into a lambda:

>>> g = Foo()
>>> g.incr = lambda self=g: incr(self)
>>> g.incr()
>>> g.incr()
>>> g.counter
2

Peter





More information about the Python-list mailing list