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

1586010002-jmsa.png

say I have a class:

class x:

def first_x_method(self):

print 'doing first_x_method stuff...'

def second_x_method(self):

print 'doing second_x_method stuff...'

and this decorator

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

how would I write another decorator otherdecorator so that:

@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...'

the same as

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...'

or in fact replace

@otherdecorator(logger.log)

class x:

with

@otherdecorator

class x:

where otherdecorator contains all the functionality

(I'm not a python person so be gentle)

解决方案

Unless there is a definite reason to use a class as a decorator, I think it is usually easier to use functions to define decorators.

Here is one way to create a class decorator trace, which decorates all methods of a class with the log decorator:

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()

yields:

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]

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值