我如何在那个方法内传递参数?
我正在使用一个叫做turtle的库。这个库里面有一个叫做onkey的命令,具体用法如下:
turtle.onkeypress(fun, key=None)
Parameters:
fun – a function with no arguments or None
key – a string: key (e.g. “a”) or key-symbol (e.g. “space”)
不过,我需要传递一个参数。有没有什么办法可以做到这一点呢?
我的代码如下:
menuInitial.py
class MenuInitial(menu.Menu):
[...]
def itemInput(self):
turtle.Screen().onkey(menu.Menu.itemUp(self), "Up")
turtle.Screen().listen()
menu.py
class Menu(drawingGeometric.rectangle):
[...]
def itemUp(self):
self.turtle.left(90)
position.position.forwardWithoutPen(self, 16)
self.turtle.right(90)
可以看到,“MenuInitial”这个类是“Menu”的子类。我正在学习面向对象编程。
1 个回答
2
看起来你只需要这样做:
class MenuInitial(menu.Menu):
[...]
def itemInput(self):
turtle.Screen().onkey(self.itemUp, "Up")
turtle.Screen().listen()
因为你把 itemUp
作为一个绑定实例方法(self.itemUp
)传给了 onkey
,而不是作为一个未绑定的方法(menu.Menu.itemUp
),所以 self
会自动作为第一个参数传进去。你可以这样做是因为 MenuInitial
是 Menu
的子类,它们共享相同的内部状态。
如果出于某种原因你确实需要给 itemUp
传递其他参数,你可以使用 functools.partial
:
from functools import partial
[...]
def itemInput(self):
func = partial(self.itemUp, "some_argument")
turtle.Screen().onkey(func, "Up")
turtle.Screen().listen()
这样你就可以有这个:
class Menu(drawingGeometric.rectangle):
[...]
def itemUp(self, argument):
print(argument) # This will print "some_argument"
self.turtle.left(90)
position.position.forwardWithoutPen(self, 16)
self.turtle.right(90)