gpt4 book ai didi

Python通过装饰类动态给类的方法添加装饰器

转载 作者:太空狗 更新时间:2023-10-29 19:36:12 25 4
gpt4 key购买 nike

假设我有一个类:

class x:

def first_x_method(self):
print 'doing first_x_method stuff...'

def second_x_method(self):
print 'doing second_x_method stuff...'

和这个装饰器

class logger:
@staticmethod
def log(func):
def wrapped(*args, **kwargs):
try:
print "Entering: [%s] with parameters %s" % (func.__name__, args)
try:
return func(*args, **kwargs)
except Exception, e:
print 'Exception in %s : %s' % (func.__name__, e)
finally:
print "Exiting: [%s]" % func.__name__
return wrapped

我将如何编写另一个装饰器 otherdecorator 以便:

@otherdecorator(logger.log)
class x:

def first_x_method(self):
print 'doing x_method stuff...'

def first_x_method(self):
print 'doing x_method stuff...'

一样
class x:
@logger.log
def first_x_method(self):
print 'doing first_x_method stuff...'

@logger.log
def second_x_method(self):
print 'doing second_x_method stuff...'

或者实际上替换

@otherdecorator(logger.log)
class x:

@otherdecorator 
class x:

otherdecorator 包含所有功能(我不是 python 人所以要温柔)

最佳答案

除非有明确的理由使用类作为装饰器,否则我认为通常使用函数来定义装饰器更容易。

这是创建类装饰器 trace 的一种方法,它使用 log 装饰器装饰类的所有方法:

import inspect


def log(func):
def wrapped(*args, **kwargs):
try:
print("Entering: [%s] with parameters %s" % (func.__name__, args))
try:
return func(*args, **kwargs)
except Exception as e:
print('Exception in %s : %s' % (func.__name__, e))
finally:
print("Exiting: [%s]" % func.__name__)
return wrapped


def trace(cls):
# https://stackoverflow.com/a/17019983/190597 (jamylak)
for name, m in inspect.getmembers(cls, lambda x: inspect.isfunction(x) or inspect.ismethod(x)):
setattr(cls, name, log(m))

return cls


@trace
class X(object):
def first_x_method(self):
print('doing first_x_method stuff...')

def second_x_method(self):
print('doing second_x_method stuff...')


x = X()
x.first_x_method()
x.second_x_method()

产量:

Entering: [first_x_method] with parameters (<__main__.X object at 0x7f19e6ae2e80>,)
doing first_x_method stuff...
Exiting: [first_x_method]
Entering: [second_x_method] with parameters (<__main__.X object at 0x7f19e6ae2e80>,)
doing second_x_method stuff...
Exiting: [second_x_method]

关于Python通过装饰类动态给类的方法添加装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5481623/

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