Pre*_*gha 9 python aop decorator
说我上课了:
class x:
def first_x_method(self):
print 'doing first_x_method stuff...'
def second_x_method(self):
print 'doing second_x_method stuff...'
Run Code Online (Sandbox Code Playgroud)
和这个装饰
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
Run Code Online (Sandbox Code Playgroud)
我将如何编写另一个装饰器,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...'
Run Code Online (Sandbox Code Playgroud)
同样的
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...'
Run Code Online (Sandbox Code Playgroud)
或实际上取代
@otherdecorator(logger.log)
class x:
Run Code Online (Sandbox Code Playgroud)
同
@otherdecorator
class x:
Run Code Online (Sandbox Code Playgroud)
其他装饰者包含所有功能(我不是蟒蛇人,所以要温柔)
unu*_*tbu 17
除非有明确的理由将类用作装饰器,否则我认为使用函数定义装饰器通常更容易.
这是创建类装饰器的一种方法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()
Run Code Online (Sandbox Code Playgroud)
收益率:
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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7700 次 |
| 最近记录: |