簡體   English   中英

將外部 function 的參數作為內部 function 的參數傳遞給 python?

[英]passing argument of outer function as argument for inner function in python?

我想通過一個外部 function 使用多種功能。 參數是一個字符串,我想在該字符串上為內部函數創建/傳遞 arguments。 這怎么可能?

def outer_function(arg1):
    
    arg2 = 'random_text' + str(arg1)
    arg3 = 'random_text' + str(arg1)
    
    def inner_function(arg2,arg3):
        global var
        do_something ...
    return inner_function()

我得到的錯誤是:

TypeError: inner_function() missing 2 required positional arguments:

不要使用global ,並且不要將變量指定為 arguments 如果您沒有將它們作為 arguments 傳遞。 函數自動訪問封閉 scope 中的值。

def outer_function(arg1):
    arg2 = 'random_text' + str(arg1)
    arg3 = 'random_text' + str(arg1)

    def inner_function():
        return arg2 + arg3

    return inner_function()

>>> outer_function(" foo ")
'random_text foo random_text foo '

您沒有通過 arguments 或return inner_funtion()下面的代碼可以提供幫助

def outer_function(arg1):
    arg2 = 'random_text' + str(arg1)
    arg3 = 'random_text' + str(arg1)
    def inner_function(arg2,arg3):
        global var
        do_something ...
    return inner_function(arg2,arg3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM