gpt4 book ai didi

python - 如何知道函数方法装饰器中的类名称?

转载 作者:行者123 更新时间:2023-11-30 23:53:37 26 4
gpt4 key购买 nike

我有一个简单的时间标记装饰器用于功能:

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

典型用法:

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

但是如何添加装饰器名称呢? (不记录:“make_torrent begin”,而是“Task.make_torrent begin”)?

最佳答案

假设装饰例程作为方法调用,您可以从 self 参数中提取类名:

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

关于python - 如何知道函数方法装饰器中的类名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5582393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com