'bind' functions into methods

Jeff Epler jepler at unpythonic.net
Sat Oct 19 22:04:06 EDT 2002


Untested ... The idea is to pass a dictionary of functions to the wrapper
object, plus the initial args, then construct the functions themselves as
needed.  You could also construct them "up front" if you prefer.

class TeaWrapper:
    def __init__(self, funcs, initial_args):
	self._funcs = funcs
	self._args = tuple(initial_args)
	# for k, v in funcs.items():
	#    setattr(self, k, self.wrapper(v))

    def __getattr__(self, name):
	try:
	    f = self._funcs[name]
	except KeyError:
	    raise AttributeError, name
    
	fun = self.wrapper(f)
	# setattr(self, name, fun) # to cache the attribute
	return fun
    def wrapper(self, f):
	# Assuming you use a Python with nested scopes:
	return lambda *args, **kw: apply(f, self.initial_args + args, kw)

    def wrapper_old_python
	# If you don't ... (move declaration of WrapperClass elsewhere for
	# efficiency)
	class WrapperClass:
	    def __init__(self, realfunc, initial_args):
		self.realfunc = realfunc
		self.initial_args = initial_args
	    def __call__(self, *args, **kw):
		return apply(self.realfunc, self.initial_args + args, kw)
	return WrapperClass(f, initial_args)

    b = TeaWrapper({'op1' = op1, 'op2' = op2}, (6,))

On Sun, Oct 20, 2002 at 12:04:15AM +0000, TeaAndBikkie wrote:
> I have a set of functions, op1(), op2(), etc. with initial argument 'n' the
> same.
> 
> I want to "bind" them into a class as methods that pass the first argument from
> an instance variable.
> 
> So far I have the following, but is there a better way to do this?
> Can I generate the methods op1, op2, etc. by looping through a list of
> functions?
> Can I put some shared code for every method call (eg. to check if n is None)?
> 
> Kind regards,
> Misha
> 
> ... sample code, on Python 2.2.1 ...
> 
> def op1(n, dude):
>     print "[[[%d -> %d]]]" % (n, dude)
> 
> def op2(n, eric, fish):
>     print "[[[%d -> %d :: %d]]]" % (n, eric, fish)
> 
> class tobj:
>     def __init__(self, n=None):
>         self.n = n
>     def op1(self, *arg, **kwargs):
>         return op1(self.n, *arg, **kwargs)
>     def op2(self, *arg, **kwargs):
>         return op2(self.n, *arg, **kwargs)
> 
> # sample usage...
> 
> op1(6, 8)
> #[[[6 -> 8]]]
> 
> op2(6, 3, 9)
> #[[[6 -> 3 :: 9]]]
> 
> a=tobj(6)
> a.op1(dude=8)
> #[[[6 -> 8]]]
> 
> a.op2(fish=9,eric=3)
> #[[[6 -> 3 :: 9]]]
> 
> b=tobj()
> b.n=7
> b.op1(8)
> #[[[7 -> 8]]]
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list