By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,746 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

Writing a function from within Python

P: n/a
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"

Thanks for any insight you might be able to offer.
Jun 27 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Aaron Scott <aa***************@gmail.comwrites:
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
Jun 27 '08 #2

P: n/a
On May 28, 4:39 pm, Aaron Scott <aaron.hildebra...@gmail.comwrote:
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"

Thanks for any insight you might be able to offer.
The short answer is "yes". The longer answer is "yes but most likely
there are better approaches to whatever you want to do". If you give a
bit more context of the general problem you're trying to solve, I'm
sure you'll get more helpful replies.

George
Jun 27 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.