Adding a method to an instance

Kirby Urner urner at alumni.princeton.edu
Sat Mar 3 01:52:02 EST 2001


Bryan Mongeau <bryan at eevolved.com> wrote:

>Kirby Urner wrote:
>
>Thanks Kirby,
>
>> In saying f.__class__, you point back to the superclass foo.
>> If you want to poke newMethod into object f alone, then you
>> should just go:
>> 
>> f = newMethod
>
>This I do not want. Maybe I should have been more clear. I would like to 
>add "newMethod" to the instance of class foo so that later I can call:
>
>f.newMethod()
>

Right, I typo'ed here too, making it worse.

>> 
>> Here's a transcript that addresses your question:
>> 
>>  >>> class foo:
>> def duh(self):
>>             print "Duh!"
>
>Is my question really that bad? :)
> 

No, it's a good question -- didn't mean to imply otherwise
with the "Duh!".  That's something I often use on my end, when
I'm doing 'foo' type testing (a local convention you might say).

>>             
>>  >>> o = foo()
>>  >>> o
>>  <__main__.foo instance at 00B9719C>
>>  >>> k = lambda x: x+2
>>  >>> k(2)
>>  4
>>  >>> o.othermethod = k
>
>k is a lambda function. I would need the new method to be able to access 
>internal class attributes, thus require the "self" parameter of class 
>methods.
>

OK, that's the nub of the issue, and a sense in which my answer
failed to answer your question.

>Okay, based on these statements and referring to my previous example, I 
>should be able to do this:
>
>def newMethod(self):
>  print self.bar
>
>f.newMethod = newMethod
>
>Problem is:
>
>f.newMethod()
>TypeError: not enough arguments; expected 1, got 0 
>
>Understandably though, this works in this case:
>f.newMethod(f)
>
>
>> I bet you get it now.
>
>Sorry, I must be really dense or something... :) I don't see how your 
>method can assist me.

Let me try again:

 >>> class foo:
	def duh(self, message):
	    self.msg = message
            print self.msg

            
 >>> o = foo()
 >>> o.duh("1-2-3 testing")
 1-2-3 testing
 >>> o.msg
 '1-2-3 testing'
 >>> def newMethod(self,newtext):
 	return self.msg + newtext

 >>> o.newMethod = newMethod
 >>> o.newMethod(o," how about it?")
 '1-2-3 testing how about it?'
 >>> dir(o)
 ['msg', 'newMethod']
 >>> dir(foo)
 ['__doc__', '__module__', 'duh']

When you invoke o.newMethod, you still have to pass your 
object as an instance, so that the internal 'self' has 
something to work with.  Is that so bad?  Only your instance
has this new method, and you are only consulting its own
internals by passing a reference to that object as the 
first parameter.

Kirby




More information about the Python-list mailing list