Writing a function from within Python
Arnaud Delobelle
arnodel at googlemail.com
Wed May 28 16:48:54 EDT 2008
Aaron Scott <aaron.hildebrandt at gmail.com> writes:
> Is it possible to change the content of a function after the function
> has been created? For instance, say I make a class:
>
> class MyClass:
> def ClassFunction(self):
> return 1
>
> And I create an object:
>
> MyObject = MyClass()
>
> Is there any way to change the content of the function, a la pseudo-
> code:
>
> MyObject.ClassFunction = "return 2"
Yes there is:
>>> class Foo(object):
... def __init__(self, x):
... self.x = x
... def bar(self):
... return self.x
...
>>> foo = Foo('spam')
>>> foo.bar()
'spam'
>>> from types import MethodType
>>> def newbar(self):
... return self.x + ', yummy!'
...
>>> foo.bar = MethodType(newbar, foo)
>>> foo.bar()
'spam, yummy!'
HTH
--
Arnaud
More information about the Python-list
mailing list