Adding methods to instances
Antoon Pardon
apardon at forel.vub.ac.be
Fri Dec 16 02:55:58 EST 2005
Op 2005-12-15, Ed Leafe schreef <ed at leafe.com>:
> 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.
But this will make the function a method to all instances of the class.
Is that what you want? From your first post I had the impression you
only wanted the function to be the method of one particular instance.
--
Antoon Pardon
More information about the Python-list
mailing list