Dynamically add methods to classes?

Fred Gansevles gansevle at cs.utwente.nl
Thu Jun 22 07:58:44 EDT 2000


In article <Sql45.1512$9W1.105781 at news-west.usenetserver.com>,
  Matthew Cline <matt at nightrealms.com> wrote:
> Is is possible to dynamically add methods to classes in Python?
>

If you take it one step furter and say: "Is it possible to dynamically
add (or change) baviour of classes in Python?", since the methods of a
class define the behaviour of that class, the answer is yes.

<SHAMELESS_PLUG>
get my dci module
(http://wwwhome.cs.utwente.nl/~gansevle/python/Dci-0.1.0.tar.gz) and use
it like this.

class A:
    def some_method(self):
        ...

class A1:
    def other_method(self):
        ....

class A2:
    def other_method(self):
        ....

...

import dci
a = A()
dci.inject(a, A1)
a.other_method()

# if you (or your code) decides that the 'other_method' of class A2
# should be used now, change the behavior.

dci.retract(a, A1)
dci.inject(a, A2)
a.other_method()

</SHAMELESS_PLUG>

> Thanks in advance.
>
>

--
-----------------------------------------------------------------------
----          Linux/Windows-NT/IntraNetware Administrator          ----
-- Whenever it sounds simple, I've probably missed something! ... Me --
-----------------------------------------------------------------------


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list