dyn added methods dont know self?

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Wed Feb 2 11:35:56 CET 2000


moonseeker at my-deja.com wrote in comp.lang.python:
> I want to add a method dynamically to an instance, how can I do this? I tried
> with exec '...' in self.__dict__, but this method doesn't know the instance
> reference 'self', so it would complain that it is called without an argument.
> Is there any other method to add a method dynamically?

You can just assign to them, self.function = etc.

I think the 'self' is only used when the function you call in an instance
is part of its class. You can add functions to an instance, but you'd
have to give the instance manually, I suppose.

class A:
   def __init__(self):
      self.text = "Spam!"
	  
# This function isn't part of the class, yet.
def foo(self):
   print self.text

# Make an instance
a = A()

# Make foo an attribute of the *instance*
a.foo = foo
# Then it has to be called with the instance
a.foo(a)  # Prints "Spam!"

# However, it can also be added to the *Class*. Then you don't get
# the problem with the extra argument, but it's added to all instances.
del a.foo
A.foo = foo
a.foo()  # Prints "Spam!" as well

So, you call a function in an instance; if it exists in the instance,
it's just executed. If it doesn't, the interpreter looks in the class,
and fills in the instance as the first argument (the "self").

Why do you need this, anyway? :)
-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
Hi! I'm a .sig virus! Join the fun and copy me into yours!



More information about the Python-list mailing list