我有一個帶有方法函式的類物件。在這個方法函式“動物”中,我有一個要呼叫的內部函式。但似乎我的內部函式沒有被呼叫,因為正確的結果應該回傳“hit here”而不是“sample text”。
這是我的課程代碼:
class PandaClass(object):
def __init__(self, max_figure):
self.tree = {}
self.max_figure = max_figure
def animal(self, list_sample, figure):
def inner_function():
if len(list_sample) == 0:
return "hit here"
inner_function()
return "sample text"
我實體化該類并使用以下代碼呼叫動物函式:
panda = PandaClass(max_figure=7)
panda.animal(list_sample=[], figure=0)
我希望代碼回傳“點擊此處”,這意味著內部函式已運行,但我得到了“示例文本”。請讓我知道如何糾正這個問題。
uj5u.com熱心網友回復:
return總是將其結果提供給呼叫它的代碼。在這種情況下,外部函式稱為內部函式,因此內部函式將其值回傳給外部函式。
如果希望外部函式回傳內部函式回傳的結果,則需要執行以下操作:
def animal(self, list_sample, figure):
def inner_function():
if len(list_sample) == 0:
return "hit here"
inner_func_result = inner_function()
if inner_func_result:
return inner_func_result
else:
return "sample text"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457216.html
