[Tutor] Demystification of Lambda Functions
Peter Otten
__peter__ at web.de
Wed Oct 28 12:54:52 EDT 2015
Steven D'Aprano wrote:
> Sometimes callbacks are particularly short and simple. Suppose you are
> programming a calculator, and you have ten buttons 0...9 which all do
> precisely the same thing: they add their own name to the calculator
> display:
>
>
> for num in range(0, 10):
> btn = Button(str(num), style="rectangle",
> callback = lambda thebtn: display.add(thebtn.name)
> )
>
>
> Much better than having to pre-define ten functions and add them to each
> of the buttons.
In this case the lambda obscures the fact that those ten functions are
identical, so I'd prefer
def add_digit(button):
display.add(button.name)
for num in range(10):
button = Button(str(num), style="rectangle", callback=add_digit)
More information about the Tutor
mailing list