Self modifying systems question

Erik Max Francis max at alcyone.com
Wed Apr 30 04:11:58 EDT 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
1
>>> c.f = lambda t: t**2
>>> c.f(2)
4
>>> c.f(3)
9
>>> c.f(4)
16
>>> c.xSquared = lambda self=c: self.x**2
>>> c.xSquared()
1
>>> c.x = 10
>>> c.xSquared()
100


-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Once the people begin to reason, all is lost.
\__/ Voltaire
    Bosskey.net: Quake III Arena / http://www.bosskey.net/q3a/
 A personal guide to Quake III Arena.




More information about the Python-list mailing list