同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
lambda Basics
The lambda’s general form is the keyword lambda, followed by one or more arguments (exactly like the arguments list you enclose in parentheses in a def header), followed by an expression after a colon:
lambda argument1, argument2,... argumentN :expression using arguments
Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs, but there are a few differences that make lambdas useful in specialized roles:
Apart from those distinctions, defs and lambdas do the same sort of work. For instance, we’ve seen how to make a function with a def statement:
>>> def func(x, y, z): return x + y + z
...
>>> func(2, 3, 4)
9
But you can achieve the same effect with a lambda expression by explicitly assigning its result to a name through which you can later call the function:
>>> f = lambda x, y, z: x + y + z
>>> f(2, 3, 4)
9
Here, f is assigned the function object the lambda expression creates; this is how def works, too, but its assignment is automatic.
Defaults work on lambda arguments, just like in a def:
>>> x = (lambda a="fee", b="fie", c="foe": a + b + c)
>>> x("wee")
'weefiefoe'
The code in a lambda body also follows the same scope lookup rules as code inside a def. lambda expressions introduce a local scope much like a nested def, which automatically sees names in enclosing functions, the module, and the built-in scope (via the LEGB rule):
>>> def knights():
... title = 'Sir'
... action = (lambda x: title + ' ' + x) # Title in enclosing def
... return action # Return a function
...
>>> act = knights()
>>> act('robin')
'Sir robin'
In this example, prior to Release 2.2, the value for the name title would typically have been passed in as a default argument value instead; flip back to the scopes coverage in Chapter 17 if you’ve forgotten why.
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏