class callable with any method name
Bengt Richter
bokr at oz.net
Tue Apr 9 21:39:31 EDT 2002
On 9 Apr 2002 13:56:09 -0700, mathieu543 at hotmail.com (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}
>########
>
>Is there a way to do that ?
>
>Thanks.
No guarantees, but try this:
>>> class A:
... def __getattr__(self, attname):
... if attname.startswith('__'): return self.__class__.__getattr__(attname)
... self._attname = attname
... return self._special
... def _special(self, *args, **kwds):
... print 'The method "%s" was called with the arguments\n%s, %s' % (
... self._attname, args, kwds
... )
...
>>> a=A()
>>> a.this_is_a_random_method(arg=1)
The method "this_is_a_random_method" was called with the arguments
(), {'arg': 1}
>>> a.yet_another_random_method(param=3)
The method "yet_another_random_method" was called with the arguments
(), {'param': 3}
>>> a.x()
The method "x" was called with the arguments
(), {}
>>> a.y
<bound method A._special of <__main__.A instance at 0x007D39E0>>
>>> a._attname
'y'
>>> a.z
<bound method A._special of <__main__.A instance at 0x007D39E0>>
>>> a.z(k=3)
The method "z" was called with the arguments
(), {'k': 3}
>>> a.z(1,2,3)
The method "z" was called with the arguments
(1, 2, 3), {}
>>> a.z(1,2,3, i=4, j=5)
The method "z" was called with the arguments
(1, 2, 3), {'i': 4, 'j': 5}
Regards,
Bengt Richter
More information about the Python-list
mailing list