class callable with any method name
Neal Norwitz
neal at metaslash.com
Tue Apr 9 17:17:03 EDT 2002
Imer wrote:
>
> Hi, I'm trying to find a way to implement a class that would allow any
> method name to be called.
> When that happens, a special method would be called and the name of
> the method that was originally called would be passed as an argument.
>
> For instance:
> ########
> class A:
> def __method_called__ (self, method_name, method_argument):
> print "The method", method_name, "was called with the argument",
> method_argument
> ########
>
> Then the following code:
> ########
> a=A()
> a.this_is_a_random_method(arg=1)
> a.yet_another_random_method(param=3)
> ########
>
> Would print out:
> ########
> The method this_is_a_random_method was called with the argument
> {'arg':1}
> The method yet_another_random_method was called with the argument
> {'param':3}
> ########
class _Ref:
def __init__(self, method, name):
self.method = method
self.name = name
def __call__(self, *args, **kw):
apply(self.method, (self.name,) + args, kw)
class A:
def __getattr__(self, attr):
return _Ref(self.__method_called__, attr)
def __method_called__(self, name, *args, **kw):
print '%s() was called with %s, %s' % (name, args, kw)
Neal
More information about the Python-list
mailing list