[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

In earlier Pythons, default arguments were required to pass all values in from enclosing
scopes explicitly, using either of these two techniques:


# use simple defaults
func = (lambda self=self, name=key: self.printit(name))

# use a bound method default
func = (lambda handler=self.printit, name=key: handler(name))

Today, we can get away with the simpler enclosing -scope reference technique for
self, though we still need a default for the key loop variable (and you may still see the
default forms in older Python code).


Note that the parentheses around the lambdas are not required here; I add them as a
personal style preference just to set the lambda off from its surrounding code (your
mileage may vary). Also notice that the lambda does the same work as a nested def
statement here; in practice, though, the lambda could appear within the call to
Button itself because it is an expression and it need not be assigned to a name. The
following two forms are equivalent:


for (key, value) in demos.items():
func = (lambda key=key: self.printit(key)) # can be nested i Button()

for (key, value) in demos.items():
def func(key=key): self.printit(key) # but def statement cannot

You can also use a callable class object here that retains state as instance attributes (see
the tutorial’s call example in Chapter 7 for hints). But as a rule of thumb, if you
want a lambda’s result to use any names from the enclosing scope when later called,
either simply name them and let Python save their values for future use, or pass them
in with defaults to save the values they have at lambda function creation time. The latter
scheme is required only if the variable used may change before the callback occurs.


When run, this script creates the same window (Figure 8-11) but also prints dialog
return values to standard output; here is the output after clicking all the demo buttons
in the main window and picking both Cancel/No and then OK/Yes buttons in each
dialog:


C:\...\PP4E\Gui\Tour> python demoDlg-print.py
Color returns => (None, None)
Color returns => ((128.5, 128.5, 255.99609375), '#8080ff')
Query returns => no
Query returns => yes
Input returns => None
Input returns => 3.14159
Open returns =>
Open returns => C:/Users/mark/Stuff/Books/4E/PP4E/dev/Examples/PP4E/Launcher.py
Error returns => ok

Now that I’ve shown you these dialog results, I want to next show you how one of them
can actually be useful.


436 | Chapter 8: A tkinter Tour, Part 1

Free download pdf