Adding methods to instances

Ed Leafe ed at leafe.com
Thu Dec 15 11:15:21 EST 2005


     Here's what I'm trying to do; please let me know if I'm nuts or  
not.

     Given a string consisting of the code you would normally define  
in a class's method, add that compiled code to an instance of that  
class so that it can be called just like any other bound method.  
Here's an example:

xx = """def dynamic(self):
    print "dynamic", self.testAtt
"""

class Test(object):
     testAtt = "sample"
     def normalMethod(self):
         print "normal", self.testAtt

testInstance = Test()
# Here's where the magic is needed
# so that the rest of this example works.
testInstance.normal()
-> 'normal', 'sample'
testInstance.dynamic()
-> 'dynamic', 'sample'

     So? Am I nuts? Or is this possible?

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com







More information about the Python-list mailing list