的沒什麼花哨的方式(我張貼在這裏的方法,這可能是做的最好的方法):
module.py:
def initialize():
print('initialize')
def do_the_thing(args):
print('doing things',args)
def function(args):
_function(args)
def firsttime(args):
global _function
initialize()
do_the_thing(args)
_function=do_the_thing
_function=firsttime
的想法很簡單:你只需添加一個間接層。 function
始終呼籲_function
,但_function
首先在firsttime
,然後永遠在do_the_thing
後。
test.py:
from module import function
function(1)
function([2,3])
運行test.py產量
initialize
('doing things', 1)
('doing things', [2, 3])
我首先想到的是使用一個發電機,但是,作爲三聯指出,有如果您使用生成器,則無法將args傳遞給該函數。所以......
這裏是使用協同程序(它不同於發電機,允許你發送參數傳遞給 - 以及從收到值 - 協程)的方式:
module.py :
def coroutine(func):
# http://www.dabeaz.com/coroutines/index.html
def start(*args,**kwargs):
cr = func(*args,**kwargs)
cr.next()
return cr
return start
def initialize():
print('initialize')
def do_the_thing(*args, **kwargs):
print('doing things', args, kwargs)
return ('result', args)
@coroutine
def _function():
args, kwargs = (yield)
initialize()
while True:
args, kwargs = (yield do_the_thing(*args, **kwargs))
_function = _function().send
def function(*args, **kwargs):
# This is purely to overcome the limitation that send can only accept 1 argument
return _function((args,kwargs))
運行
print(function(1, x = 2))
print(function([2, 3]))
產生
initialize
('doing things', (1,), {'x': 2})
('result', (1,))
('doing things', ([2, 3],), {})
('result', ([2, 3],))
谷歌爲「蟒蛇裝飾」 – Triptych
我沒有看到一個裝飾如何能做到這一點,條件仍然存在,如果你測試@graphox解決方案,使用一個生成器按預期工作,雖然它感覺有點奇怪。 –