Adding a method to an instance

Bryan Mongeau bryan at eevolved.com
Sat Mar 3 01:31:14 EST 2001


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()

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

Is my question really that bad? :)
 
>             
>  >>> 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.

>  >>> o.othermethod(3)
>  5
>  >>> dir(o)
>  ['othermethod']
>  >>> dir(foo)
>  ['__doc__', '__module__', 'duh']
>  >>> o.__class__
>  <class __main__.foo at 00BB3ECC>
>  >>> foo
>  <class __main__.foo at 00BB3ECC>
>  >>> o
>  <__main__.foo instance at 00B9719C>
> 
> Note re the last three commands:  o.__class__ is a pointer to
> the class foo in memory, so you would be adding to the superclass
> to put a method in there.  You want to insert your method into
> the instance/object, so don't involve its __class__.

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.

-- 
<=====================================>
Bryan Mongeau
Lead Developer, Director
eEvolved Real-Time Technologies Inc.
Website:    http://www.eevolved.com
Public key: http://eevolved.com/bcm.pk
<=====================================>

"The eternal mystery of the world is its comprehensibility."-- Einstein




More information about the Python-list mailing list