I have a Button
class that has a variable, when_pressed
, that is meant to be a function. For the sake of the question, let's assume that it will always be a function and not something like an int
. When your instance of the Button
class is pressed, the function contained in when_pressed
gets called. So you could do this:
我有一个Button类,它有一个变量when_pressed,它是一个函数。为了这个问题,让我们假设它总是一个函数,而不是像int这样的东西。当按下Button类的实例时,将调用when_pressed中包含的函数。所以你可以这样做:
def pressed():
print("Pressed")
button = new Button()
button.when_pressed = pressed
This will print Pressed
when the button is pressed. Makes sense.
这将在按下按钮时打印按下。说得通。
But I won't be needing that function anywhere else. I am dealing with a low-memory environment, so it would be easier to do something like this:
但我不会在其他任何地方需要这个功能。我正在处理低内存环境,所以做这样的事情会更容易:
button = new Button()
button.when_pressed = function():
print("Pressed")
You could do this in Javascript, so I think it's possible in Python too. But I can't find anything on it. How can I do this?
你可以在Javascript中做到这一点,所以我认为它也可以在Python中实现。但我找不到任何东西。我怎样才能做到这一点?
2 个解决方案
#1
5
Use a lambda
function:
使用lambda函数:
button.when_pressed = lambda: print('pressed')
Here's a good chance for you to learn about them in case you haven't: lambda functions
这是一个很好的机会让你了解它们,如果你没有:lambda函数
#2
2
Use a lambda:
使用lambda:
something = lambda: print("Hello")
#1
5
Use a lambda
function:
使用lambda函数:
button.when_pressed = lambda: print('pressed')
Here's a good chance for you to learn about them in case you haven't: lambda functions
这是一个很好的机会让你了解它们,如果你没有:lambda函数
#2
2
Use a lambda:
使用lambda:
something = lambda: print("Hello")