Python 2.7 python2.7装饰其他外部模块中使用的外部模块的函数
我有3个文件Python 2.7 python2.7装饰其他外部模块中使用的外部模块的函数,python-2.7,decorator,Python 2.7,Decorator,我有3个文件a.pyc,b.pyc,和c.py 文件a.pyc: def(x): #用x做点什么,然后得到y 返回y 文件b.pyc: 从导入f def g(x): z=f(x) #处理z得到w 返回w 我不能修改这些文件,但我可以c.py,其中的代码将在b.pyc之前执行。问题是,我可以将文件c.py中的decorator(以及如何)添加到函数f中,何时在g中调用函数f,decorator中的代码将执行 # a.py class A: def __init__(self):
a.pyc
,b.pyc
,和c.py
文件a.pyc
:
def(x):
#用x做点什么,然后得到y
返回y
文件b.pyc
:
从导入f
def g(x):
z=f(x)
#处理z得到w
返回w
我不能修改这些文件,但我可以c.py
,其中的代码将在b.pyc
之前执行。问题是,我可以将文件c.py
中的decorator(以及如何)添加到函数f
中,何时在g
中调用函数f
,decorator中的代码将执行
# a.py
class A:
def __init__(self):
pass
def f(self, x):
xx = x+100
print xx
return xx
# b.py
from a import A
class B:
def __init__(self):
self.a = A()
def g(self):
x = self.a.f(3) + 1000
print x
return x
# c.py
from functools import wraps
from a import A
def run_before(module, func_name):
def decorator(callback):
func = getattr(module, func_name)
@wraps(func)
def run_before_wrapper(*args, **kwargs):
callback(*args, **kwargs)
return func(*args, **kwargs)
setattr(module, func_name, run_before_wrapper)
return callback
return decorator
def run_after(module, func_name):
def decorator(callback):
func = getattr(module, func_name)
@wraps(func)
def run_before_wrapper(*args, **kwargs):
res = func(*args, **kwargs)
callback(*args, **kwargs)
return res
setattr(module, func_name, run_before_wrapper)
return callback
return decorator
@run_before(A, 'f')
def sstart(*args, **kwargs):
print "start"
@run_after(A, 'f')
def sstop(*args, **kwargs):
print "sstop"
from b import B
bb = B()
print bb.g()
返回
start
103
sstop
1103
1103