简体   繁体   中英

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.

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

The movePaddle function takes a paddle and a direction. i want to bind this to the onkeypress function of turtle.

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

Running above code would execute the movepaddle function once. which is obviously not the desired behaviour. The desired behaviour is that whenever the onkeypress eventhandler encounters a "w" key. it executes the movepaddle function with the given "paddleA" and "up" parameters.

You can use the functools.partial

The partial function receives a function and parameters, and returns a callable that calls the supplied function with the given parameters.

import functools

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

You can read more about it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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