Adding methods to instances

Ed Leafe ed at leafe.com
Thu Dec 15 13:05:32 EST 2005


On Dec 15, 2005, at 11:51 AM, Lawrence Oluyede wrote:

>>      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()

     Thanks! I knew I had done this before. My mistake was that I was  
setting the exec'd code to the instance, and not to the class. That  
works, but makes it a function, which doesn't automatically get sent  
the 'self' reference.

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




More information about the Python-list mailing list