Adding methods to instances

Ben Hutchings ben-public-nospam at decadentplace.org.uk
Fri Dec 16 11:39:32 EST 2005


Antoon Pardon <apardon at forel.vub.ac.be> wrote:
> 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.

How about:

    def bind(fun, arg):
        return lambda *a, **k: fun(arg, *a, **k)

    t.dynamic = bind(dynamic, t)

-- 
Ben Hutchings
The world is coming to an end.	Please log off.



More information about the Python-list mailing list