Including a Method to an Existing Object Instance
What you are seeking is
setattr I think.
Utilize this to set a feature on an object.
>>> def printme(s): print repr(s) >>> class A: pass >>> setattr(A,'printme',printme) >>> a = A() >>> a.printme() # s becomes the implicit 'self' variable < __ main __ . A instance at 0xABCDEFG>
In Python, there is a distinction in between features and also bound methods.
>>> def foo(): ... print "foo" ... >>> class A: ... def bar( self ): ... print "bar" ... >>> a = A() >>> foo <function foo at 0x00A98D70> >>> a.bar <bound method A.bar of <__main__.A instance at 0x00A9BC88>> >>>
Bound methods have actually been "bound" (just how detailed) to an instance, which instance will certainly be passed as the first argument whenever the method is called.
Callables that are features of a class (in contrast to an instance) are still unbound, though, so you can change the class definition whenever you desire:
>>> def fooFighters( self ): ... print "fooFighters" ... >>> A.fooFighters = fooFighters >>> a2 = A() >>> a2.fooFighters <bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>> >>> a2.fooFighters() fooFighters
Previously specified circumstances are upgraded too (as long as they have not bypassed the feature themselves):
>>> a.fooFighters() fooFighters
The trouble comes when you intend to attach a method to a solitary instance:
>>> def barFighters( self ): ... print "barFighters" ... >>> a.barFighters = barFighters >>> a.barFighters() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: barFighters() takes exactly 1 argument (0 given)
The function is not instantly bound when it's affixed straight to an instance:
>>> a.barFighters <function barFighters at 0x00A98EF0>
To bind it, we can make use of the MethodType function in the types module:
>>> import types >>> a.barFighters = types.MethodType( barFighters, a ) >>> a.barFighters <bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>> >>> a.barFighters() barFighters
This time various other circumstances of the class have actually not been influenced:
>>> a2.barFighters() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: A instance has no attribute 'barFighters'
In Python ape patching usually functions by overwriting a class or features trademark with your very own. Below is an instance from the Zope Wiki :
from SomeOtherProduct.SomeModule import SomeClass def speak(self): return "ook ook eee eee eee!" SomeClass.speak = speak
That code will certainly overwrite/create a method called talk on the class. In Jeff Atwood's recent post on monkey patching. He reveals an instance in C# 3.0 which is the existing language I make use of for job.