亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當我調用內部/裝飾函數時,我可以將參數傳遞到裝飾器函數中嗎?

當我調用內部/裝飾函數時,我可以將參數傳遞到裝飾器函數中嗎?

慕桂英4014372 2023-09-19 14:49:17
希望這個術語是正確的。我有這個裝飾器函數,它讀取一個文本文件:def read_commands(inner, path=BATCH_PATH):    with open(path) as f:        commands = ['python ' + line.replace('\n', '') for line in f]    def wrapper(*args, **kwargs):        for command in commands:            inner(command, *args, **kwargs)    return wrapper這是它裝飾的功能之一:@read_commandsdef execute_multi_commands(command, count):    LOG.info(f'Executing command {count}: {command}')    os.system(command)    count += 1我希望能夠在調用時更改默認路徑execute_multi_commands,就像我的main:def main():    parser = argparse.ArgumentParser()    parser.add_argument('-b', '--batch', action='store', type=str, dest='batch')    args = parser.parse_args()        count = 1    execute_multi_commands(count, path=args.batch)然而,顯然這不起作用,因為pathis not a argument in execute_multi_commands. 當我調用時,我是否可以傳遞path給裝飾器函數?- 或者,更有可能的是,任何功能等效的替代方案?read_commandsexecute_multi_commands
查看完整描述

1 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

你不能,至少你的裝飾器的編寫方式是這樣。當你裝飾一個函數時,它類似于:


def execute_multi_commands(command, count):

    LOG.info(f'Executing command {count}: {command}')

    os.system(command)

    count += 1


execute_multi_commands = read_commands(execute_multi_commands)

所以在這之后,read_commands已經被執行了,并且文件已經被讀取了。


您可以做的是更改裝飾器以讀取包裝器中的文件,例如:


def read_commands(inner, path=BATCH_PATH):


    def wrapper(*args, **kwargs):


        if "path" in kwargs:

            path_ = kwargs.pop("path")

        else:

            path_ = path


        with open(path_) as f:

            commands = ['python ' + line.replace('\n', '') for line in f]


        for command in commands:

            inner(command, *args, **kwargs)


    return wrapper

...但這意味著每次調用修飾函數時都會讀取該文件,這與您之前所做的略有不同。


查看完整回答
反對 回復 2023-09-19
  • 1 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號