我想弄清楚如何將一個函式指向一個函式。我想要做的是回答一個提示問題 y/n 會運行某個函式。當我輸入 y 時,它將運行兩個函式,而不是僅運行函式 1。
謝謝!
def company_type(question, public_company, private_company):
print("Is the target company public on NYSE or NASDAQ?")
prompt = f'{question} (y/n)'
ans = input(prompt)
if ans == 'y':
return (public_company)
if ans == 'n':
print("Please enter financial infomation manually.")
return (private_company)
company_type("public_company", "private_company", 1)
# function 1
def public_company():
return (print("Success 1"))
public_company()
# function 2
def private_company():
return (print("Success 2"))
private_company()
uj5u.com熱心網友回復:
你絕對可以回傳一個函式供以后使用——這是函式式編程的精髓,也是在 python 中將函式作為第一類物件的原因~ Guido Van Rossum。
重要的是要記住括號表示函式呼叫,而沒有括號表示函式物件。
def public_company():
print("we do what public companies do")
def private_company():
print("we do what private companies do")
def choose_company():
ans = input("Is the target company public?")
if ans == 'y':
return public_company # no parens
else:
return private_company # no parens
if __name__ == '__main__':
# assign the returned function to selected_company
selected_company = choose_company()
# calling selected_company() will call the selected function
selected_company() # use parens, this is a function call!
uj5u.com熱心網友回復:
你真的不想回傳一個函式。您只希望一個函式呼叫另一個函式。這樣做是這樣的:
# function 1
def public_company():
return print("Success 1")
# function 2
def private_company():
return print("Success 2")
def company_type(question, public_company, private_company):
print("Is the target company public on NYSE or NASDAQ?")
prompt = f'{question} (y/n)'
ans = input(prompt)
if ans == 'y':
return public_company()
else:
print("Please enter financial information manually.")
return private_company()
company_type("some question", public_company, private_company)
并且請注意 Python 中的 return 陳述句不使用一組額外的括號。這是一個C成語。
uj5u.com熱心網友回復:
錯誤:-
function不是關鍵字。- 我們可以通過以下方式呼叫函式:-
<function_name>()。
# function 1
def public_company():
print("Success")
# function 2
def private_company():
print("Success")
def company_type():
print("Is the target company public on NYSE or NASDAQ?")
prompt = 'Is your company a public company? (y/n)'
ans = input(prompt)
if ans == 'y':
public_company()
if ans == 'n':
print("Please enter financial information manually.")
private_company()
company_type()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354030.html
