redefining a function through assignment

Peter Hansen peter at engcorp.com
Fri Sep 9 09:31:02 EDT 2005


> Daniel Britt wrote:
> 
>> I am new to Python so if there is an obvious answer to my question 
>> please forgive me. Lets say I have the following code in mod1.py
>>
>> class test:
>>    def func1(self):
>>       print 'hello'
>>
>>
>> Now lets say I have another file called main.py:
>>
>> import mod1
>>
>> inst = mod1.test()
>> inst.func1()
>>
>>
>> This will print out hello. Now if I added the following to main:
>> def newFunc(var):
>>    print 'new method'
>>
>> mod1.test.func1 = newFunc

If what you're really saying is that you would like to be able to change 
the method that is called *for the instance named 'inst'*, but without 
the problem you mentioned, then there is a way, and you don't need the 
complexity of meta-classes and such.

 >>> class test:
...   def func1(self):
...     print 'hello'
...
 >>> inst = test()
 >>> inst.func1()
hello
 >>>
 >>> def newFunc(self):
...   print 'new method'
...
 >>> import new
 >>> inst.func1 = new.instancemethod(newFunc, test)
 >>> inst.func1()
new method
 >>> inst2 = test()
 >>> inst2.func1()
hello


(This might not have anything to do with your real use case, but since 
"plugin" covers a lot of territory, this might solve whatever problem 
you thought you would have.  If not, well, at least it's probably new to 
you and might be useful in the future. :-)  )

-Peter



More information about the Python-list mailing list