[Tutor] Dynamically changing a class
Ricardo Aráoz
ricaraoz at gmail.com
Tue Sep 4 15:59:37 CEST 2007
Alan Gauld wrote:
> "Jason Doege" <jdoege at da-test.com> wrote
>
>> I'd like to change the behavior of a class' member function
>> dynamically
>> such that, once changed, all objects of the type would see the new
>> behavior.
>
>>>>> class MyClass (object) :
>> def mfunc(self, data):
>> print 'pre change behavior'
>>
>>>>> aMyClassObj = MyClass()
>>>>> aMyClassObj.mfunc(data)
>> pre change behavior
>>>>> def MyClass.mfunc(self, data): #this does not work :-(
>> print 'post change behavior'
>
> You need to do it thusly:
>
> def newfunc(self, data):
> print 'post change'
> MyClass.mfunc = newfunc
>
> That seems to work.
> I'm slightly surprised since I didn't know if it would, but it seems
> to!
>
So lets take it a notch up.
Wanted to change the mfunc method but ONLY for an instance, not a class:
>>> MyObj = MyClass()
>>> MyObj.mfunc(data)
pre change behavior
>>> MyObj.mfunc = newfunc
>>> MyObj.mfunc(data)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: newfunc() takes exactly 2 arguments (1 given)
and this did not work (mfunc will ask for 2 parameters). So I tried :
>>> MyObj.mfunc = newfunc(MyObj)
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'Myobj' is not defined
this didn't work either.
Any ideas?
More information about the Tutor
mailing list