python装饰器在类中的实现

python

class Test():

xx = False

def __init__(self):

pass

def test(func):

def wrapper(self, *args, **kwargs):

print(self.xx)

return func(self, *args, **kwargs)

return wrapper

@test

def test_a(self,a,b):

print(f'ok,{a} {b}')

if __name__=='__main__':

t=Test()

t.test_a('a','ab')

 新写的例子,封装了一个调用API,需要保存用户调用的一些信息

def log(func):

@functools.wraps(func)

def wrapper(self, *args, **kwargs):

start = time.time()

result, success, err = None, None, None

try:

result = func(self, *args, **kwargs)

success = True

except Exception as e:

err = e

end = time.time()

log_dict = {'tableName': args[0],

'operation': func.__name__,

'startTime': time.strftime(time_format, time.localtime(start)),

'endTime': time.strftime(time_format, time.localtime(end)),

'elapsedTime': int(end - start),

'success': success,

'errMsg': err,

'account': self.account}

print(json.dumps(log_dict))

return result

以上是 python装饰器在类中的实现 的全部内容, 来源链接: utcz.com/z/387720.html

回到顶部