adding instance methods after instantiation
Marcin 'Qrczak' Kowalczyk
qrczak at knm.org.pl
Sat Jun 23 10:28:34 EDT 2001
Sat, 23 Jun 2001 11:45:06 +0000 (UTC), Lee Harr <missive at frontiernet.net> pisze:
> 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).
--
__("< Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
\__/
^^ SYGNATURA ZASTĘPCZA
QRCZAK
More information about the Python-list
mailing list