开发者

How to know name of class in decorator for function-method?

I have a simple timemark-decorator for function:

def dec_timemark(f):
    def tmp(*args, **kwargs):
        sys.stdout.write(strftime("%d.%m.%Y %H:%M:%S") + ' ' + f.__name__ +
                                                         ' begin' + "\n开发者_开发问答" )
        res = f(*args, **kwargs)
        sys.stdout.write(strftime("%d.%m.%Y %H:%M:%S") + ' ' + f.__name__ +
                                                         ' end' + "\n"     )
        return res
    return tmp

typical usage:

class Task():
    @dec_timemark
    def make_torrent():
        sleep(10)

But how to add to this decorator name of the class? (Not to log: "make_torrent begin", but "Task.make_torrent begin" for example ) ?


Assuming that the decorated routine is invoked as a method, you can pull the classname out of the self parameter:

def dump(f):
    def decorated(self, *args, **kwargs):
        print 'Class: {0}'.format(self.__class__.__name__)
        print 'Args passed to decorated function: {0}'.format(args)
        print 'Keyword args passed to decorated function: {0}'.format(kwargs)
        return f(self, *args, **kwargs)
    return decorated

class Test(object):
    """
    >>> Test().test('arg1', 'arg2', kwarg1='kwval1')
    Class: Test
    Args passed to decorated function: ('arg1', 'arg2')
    Keyword args passed to decorated function: {'kwarg1': 'kwval1'}
    """
    @dump
    def test(*args, **kwargs):
        pass


It's not possible to access that information within the scope of dec_timemark() itself, since the class doesn't exist yet. However, when tmp() is called, the first argument will be self, since .make_torrent() is being called as an instance method. Thus, type(self).__name__ should give you the class name.

Modifying your example:

def dec_timemark(f):
    def tmp(self, *args, **kwargs):
        cname = type(self).__name__
        sys.stdout.write(strftime("%d.%m.%Y %H:%M:%S") + ' ' + cname + '.' + f.__name__ +
                                                     ' begin' + "\n" )
        res = f(self, *args, **kwargs)
        sys.stdout.write(strftime("%d.%m.%Y %H:%M:%S") + ' ' + cname + '.' + f.__name__ +
                                                     ' end' + "\n"     )
        return res
    return tmp
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜