我已经用 Java 编程了 ~2 年,刚刚开始学习 Python(大约 1 周)和 PyGame,一直想创建一个简单的按钮类,但我不想要按钮(按下时会发生什么)被硬编码。在 Python/PyGame 中执行此操作的最佳方法是什么?
我还想过在构造函数中有一个变量,它在调用时被设置为一个函数,例如: def __init__(self, func)
并称呼为
act = Action () obj = 按钮( Action ),
我认为这行不通,但我会在测试时回复大家。
在 Java 中,它会这样调用:
button = new Button("Text");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.out.println("ACTION");
}
}
请您参考如下方法:
我知道可以将一个函数对象传递给另一个函数的唯一方法是传递它的标识符:
# listener function
def listener():
print('listening...')
class Button:
def __init__(self, mouse_listener):
mouse_listener() # you call the function inside __init__
button = Button(listener)
在 Python 中,你可以接收一个函数作为参数,因为函数实际上是对象,但它们是特殊的对象,因为它们可以被调用或者它们是可调用对象,实际上你也可以显式调用他们的 __call__ 调用函数的默认函数:
listener.__call__()
但通常你不会那样做。
