modifying method behaviour

Hannu Kankaanpää hanzspam at yahoo.com.au
Wed Aug 27 18:22:19 CEST 2003


Nicodemus <nicodemus at globalite.com.br> wrote in message news:<mailman.1061945272.22252.python-list at python.org>...
> Craig Zoretich wrote:
> 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




More information about the Python-list mailing list