Adding methods to instances

Lawrence Oluyede raims at dot.com
Thu Dec 15 11:51:32 EST 2005


Il 2005-12-15, Ed Leafe <ed at leafe.com> ha scritto:
>      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?

Yes it is, use exec() to turn your string in valid Python code
and bind the dynamic function as a method of class Test

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

exec xx

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

t = Test()
Test.dynamic = dynamic
t.dynamic()



-- 
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"



More information about the Python-list mailing list