声明 python 存储函数的变量,但不声明 运行 它

Declare python variable that stores a function, but not run it

我正在尝试声明一个 python 变量来存储具有所需参数的函数,但是当我 运行 它时,它 运行 是最后声明的变量。我试图将它存储在一个变量中,当我写变量名时,它 运行 是带有关联参数的函数。它意味着 运行 在一个名为 Processing:

的程序中
size(1000,500)
background(255,255,255)
cred = fill(255,0,0)
corange = fill(255,127,0)
cyellow = fill(255,255,0)
cgreen = fill(0,255,0)
cblue = fill(0,0,255)
cpurple = fill(143,0,255)

mcolors = [cred,corange,cyellow, cgreen, cblue, cpurple]
y=0

def palette():
    global y
    global mcolors
    for i in mcolors:
        i
        rect(0,y,20,20)
        y+=22
palette()   `

一种方法是将调用包装在 lambda 函数中:

cred = lambda: fill(255, 0, 0)

要调用它,您仍然需要 (),即:

i()

但是我认为在这种情况下,最好只存储颜色值而不是实际的函数引用,即:

cred = (255, 0, 0)

这将创建值的 元组 (有点像不可变列表)。它不同于函数调用括号。稍后您可以将它们传递给循环中的函数:

fill(*i)

星号运算符将使它使用元组中的值作为单独的参数而不是一个参数。