modifying method behaviour

Nicodemus nicodemus at globalite.com.br
Wed Aug 27 17:26:55 EDT 2003


Hannu Kankaanpää wrote:

>Nicodemus <nicodemus at globalite.com.br> wrote in message news:<mailman.1061945272.22252.python-list at python.org>...
>  
>
>>Use the new descriptor protocol:
>>
>>class logmethod(object):
>>
>>    def __init__(self, func):
>>        self.func = func
>>
>>    def __get__(self, obj, class_):
>>        def logger(s, *args, **kwargs):
>>            result = self.func(s, *args, **kwargs)
>>            params = [repr(x) for x in args]
>>            params += ['%s=%r' % (name, value) for name, value in 
>>kwargs.items()]
>>            print 'LOG: %s(%s)' % (self.func.__name__, ', '.join(params))
>>            return result
>>        return logger.__get__(obj)
>>    
>>
>
>Actually, since we're accessing functions, not variables,
>descriptors aren't useful. This would do also:
>
>def logmethod(func):
>    def logger(s, *args, **kwargs):
>        result = func(s, *args, **kwargs)
>        params = [repr(x) for x in args]
>        params += ['%s=%r' % (name, value) for name, value in kwargs.items()]
>        print 'LOG: %s(%s)' % (func.__name__, ', '.join(params))
>        return result
>    return logger
>  
>

Actually, methods are also descriptors, so the use that I indicated is 
valid. But I agree that your logmethod function works, and actually it's 
better, since it is simpler... for this case, descriptors are really 
overkill. Thanks for the remainder.

Regards,
Nicodemus.






More information about the Python-list mailing list