Add methods to a class at runtime?
Gerhard Häring
gerhard.haering at gmx.de
Sun Sep 1 17:44:38 EDT 2002
* Robert Oschler <Oschler at earthlink.net> [2002-09-01 17:19 -0400]:
> Ok bear with me guys (Gerhard and Peter). I'm not lazy, the reason I
> don't test certain things I should is because Python is capable of
> such amazing introspective dynamism that, having a _very_ long
> experience bank in strongly typed "static" languages like C++ and
> Pascal, I find I don't even consider yet even trying certain
> possibilies that Python is capable of.
> Some interesting tidbits I found while trying out your suggestions, as
> you will see in the two ".py" files that follow, I discovered that to
> create a method you can dynamically add to a class _instance_, you
> need to omit the 'self' parameter in the method declaration.
Yep, I found that out today too, when I wrote my last reply. Though I've
never used that in real life.
> [...] I'm running 2.1.1, anybody know if 2.2.2 is going "disable"
> either of these abilities?
It will be strictly (even binary) compatible with Python 2.2.{0|1}, so
the answer is that these features will stay.
> (class or class instance dynamic method addition). I saw a note about
> such activities requiring a "dynamic" keyword, which is fine.
I never saw such a note. Maybe you were reading a message from the
(dormant) types-sig, where ways to introduce optional (!) stronger
typing into Python are discussed. I never saw Guido make any comments
about removing dynamic features from Python, though. With /one/
exception, which you didn't mention, yet: assigning to the __class__
attribute:
>>> class Foo:
... def action(self): print "foo"
...
>>> class Bar:
... def action(self): print "bar"
...
>>> foo = Foo()
>>> foo.__class__
<class __main__.Foo at 0x80d39ac>
>>> foo.action()
foo
>>> foo.__class__ = Bar
>>> foo.action()
bar
>>> foo.__class__
<class __main__.Bar at 0x80e75c4>
>>>
AFAIK Guido isn't too fond of this feature. I guess it might go away
some day.
Gerhard
--
mail: gerhard <at> bigfoot <dot> de registered Linux user #64239
web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))
More information about the Python-list
mailing list