Self modifying systems question

Erik Max Francis max at
Wed Apr 30 10:11:58 CEST 2003

Sten Kvamme wrote:

> Self modifying code is a well known technology. Has anyone done this
> in
> Python? What I'm seeking for is examples of software that adds to
> itself (methods and variables) in runtime. I'd like an instantiated
> object to
> be able to add a method to itself.

Oh yeah, Python can do this just fine.  Dynamic attribute addition is
actually the normal way things are done; after all, that's all that an
__init__ method does (provided the class doesn't have __slots__) -- it
adds attributes.  It's customary, for maintainability's sake, to add
everything all at once, but there's no reason you can't add more later.

Same thing with "methods" -- all you really need is an attribute that's
callable.  If you want something that has access to the self instance,
you can just pass that along as well.

>>> class C: pass
>>> c = C()
>>> c
<__main__.C instance at 0x8159244>
>>> dir(c)
['__doc__', '__module__']
>>> c.x = 1
>>> c.x
>>> c.f = lambda t: t**2
>>> c.f(2)
>>> c.f(3)
>>> c.f(4)
>>> c.xSquared = lambda self=c: self.x**2
>>> c.xSquared()
>>> c.x = 10
>>> c.xSquared()

 Erik Max Francis / max at /
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Once the people begin to reason, all is lost.
\__/ Voltaire Quake III Arena /
 A personal guide to Quake III Arena.

More information about the Python-list mailing list