你如何撰寫一個函式 f,它接受另一個函式 g 作為引數,但是函式 g 的引數會根據函式 f 中發生的情況而動態變化?
一個偽代碼示例是:
def function(another_function(parameters)): # another function passed as an argument, with parameters
for i in range(10):
print(another_function(i))
因此,當 i 迭代時,函式 f 每次都會使用新引數 i 呼叫。這怎么可能實施?
我發現可以使用 *args 作為引數,但沒有看到它是如何實作的。
干杯
uj5u.com熱心網友回復:
讓我們創建一個帶有兩個引數的函式。第一個引數是對函式的參考,另一個是該函式要使用的引數
def func1(func, p):
func(p)
func1(print, 'Hello world!')
所以我們呼叫 func1 并參考內置的print函式(不必是內置的 - 可以是范圍內的任何函式)
輸出:
Hello world!
uj5u.com熱心網友回復:
你的例子幾乎是正確的。你可以簡單地寫:
def function(another_function):
for i in range(10):
print(another_function(i))
在 Python 中,函式只是物件,就像數字、字串和串列一樣,因此不需要像這樣使用特殊語法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532029.html
標籤:Python功能句法
