python 动态添加装饰器_Python通过装饰类动态地将装饰器添加到类的方法中

本文探讨了如何在Python中使用装饰器进行方法的增强和管理。示例展示了如何创建一个名为`logger`的装饰器用于记录方法的进入、执行异常和退出,并提出如何创建另一个装饰器`otherdecorator`来组合`logger`,使得类的方法能够方便地应用多个装饰器,同时保持代码的简洁和可读性。
摘要由CSDN通过智能技术生成

说我有一个班:

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:

其他设备包含所有功能

(我不是一个Python,所以温柔)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值