[英]Python functions calling functions inside functions
在 Python 中,假設我有以下代碼:
def func0():
print("This is func0")
def func1():
print("func1 calls func0")
func0()
def func2():
def func21():
print("This is func21")
print("func2 can call func0")
func0()
print("It can also call funct21")
func21()
func_0()
func_1()
func_2()
有沒有辦法讓 func1() 調用 func21()? 還是我只需要將 func21() 從 func2() 中取出?
我在網上找不到任何東西,以為我會在這里嘗試。
TIA!
如果由於某些特定原因無法將 function 移出,您可以嘗試將 func21 直接添加到本地 scope(在您發送的示例中,function 定義在封閉范圍內)。
def func0():
print("This is func0")
def func1():
print("func1 calls func0")
func0()
func21()
def func2():
locals()["func21"] = lambda:print("This is func21")
print("func2 can call func0")
func0()
print("It can also call funct21")
func21()
func0()
func1()
func2()
或者
def func0():
print("This is func0")
def func1():
print("func1 calls func0")
func0()
func21()
def func2():
def func21():
print("This is func21")
locals()["func21"] = func21
print("func2 can call func0")
func0()
print("It can also call funct21")
func21()
func0()
func1()
func2()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.