adding instance methods after instantiation

Lee Harr missive at frontiernet.net
Sat Jun 23 11:03:41 EDT 2001


On 23 Jun 2001 14:28:34 GMT, Marcin 'Qrczak' Kowalczyk <qrczak at knm.org.pl>:
> Sat, 23 Jun 2001 11:45:06 +0000 (UTC), Lee Harr <missive at frontiernet.net>:
> 
>> Is there some way to make m2 an instance method so that
>> it will automatically get passed c1 as its first
>> argument?
> 
> You are putting it in a concrete instance. In this case you know
> the instance to pass:
>     c1.m2 = lambda *args, **kwargs: m2(c1, *args, **kwargs)
> 
> Note that it requires 'from __future__ import nested_scopes' if used
> inside a function. Without that feature m2 and c1 would have to be
> passed using the default argument trick and the function could not
> be fully general (these default arguments would not be available
> in kwargs).
> 
> It creates a reference cycle. Newer Python versions garbage collect
> this, although not immediately; older don't.
> 
> If the function is used only in one instance, you could as well refer
> to self as c1 in its body instead of through the argument, and
> the above would not be needed.
> 
> If you put the method in a class instead of in the instance
> (i.e. c.m2 = m2), it will be passed the instance implicitly
> (and it will be available from all instances).

Thank you. I think this is going to do what I want:

class c:
  def __init__(self):
    self.a1 = 1

def m1(self):  #outside of class definition
  self.a2 = 2

c1 = c()
c.m1 = m1
c1.m1()
c1.a2


So, if I were then to pickle c1 (or put it in to ZODB) it would
still have the m1 method when it came back out of storage?

Does this make sense, or should I really be looking for a way
to subclass c and then copy over any data from c1 to a new
instance of the new subclass?


> 
> -- 
>  __("<  Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
>  \__/
>   ^^                      SYGNATURA ZASTÊPCZA
> QRCZAK



More information about the Python-list mailing list