简体   繁体   English

Python:将带有参数的 function 传递给 function

[英]Python: Pass a function with parameters to a function

I really am not sure if im missing something extremely basic but im trying to pass a function another function with parameters without executing it.我真的不确定我是否遗漏了一些非常基本的东西,但我试图通过一个 function 另一个 function 参数而不执行它。

def movePaddle(paddle, direction):
    y = paddle.ycor()
    y += 20
    paddle.sety(y)

The movePaddle function takes a paddle and a direction. movePaddle function 带一个桨和一个方向。 i want to bind this to the onkeypress function of turtle.我想将此绑定到龟的onkeypress function。

wn.listen()
wn.onkeypress(movepaddle(paddleA, "up"), "w")

Running above code would execute the movepaddle function once.运行上述代码将执行一次 movepaddle function。 which is obviously not the desired behaviour.这显然不是理想的行为。 The desired behaviour is that whenever the onkeypress eventhandler encounters a "w" key.期望的行为是每当 onkeypress 事件处理程序遇到“w”键时。 it executes the movepaddle function with the given "paddleA" and "up" parameters.它使用给定的“paddleA”和“up”参数执行 movepaddle function。

You can use the functools.partial您可以使用functools.partial

The partial function receives a function and parameters, and returns a callable that calls the supplied function with the given parameters. partial function 接收 function 和参数,并返回一个可调用的,该可调用使用给定的参数调用提供的 function。

import functools

wn.listen()
wn.onkeypress(functools.partial(movepaddle, paddleA, "up")), "w")

You can read more about it here你可以在这里阅读更多关于它的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM