Binding first parameter of method to constant value
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri May 18 09:10:23 EDT 2012
On Fri, 18 May 2012 14:14:33 +0200, Johannes Bauer wrote:
> Hi group,
>
> I'm trying to dynamically add methods to a class at runtime. What I
> would like to do is have them all delegated to one common function which
> is called with the name of the function as first parameter. I.e.:
[...]
Here's one way:
import types
class K(object):
def _dispatcher(self, name, *args):
print "called from", name, args
def __init__(self):
setattr(self, 'foometh',
types.MethodType(
lambda self, *args: self._dispatcher('foometh', *args),
self, self.__class__)
)
setattr(self, 'barmeth',
types.MethodType(
lambda self, *args: self._dispatcher('barmeth', *args),
self, self.__class__)
)
--
Steven
More information about the Python-list
mailing list