这是如何工作的:
def writer():
title = "Mr"
name = (lambda x: title + ' ' + x)
return name
writer("Bond")
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: writer() takes 0 positional arguments but 1 was given
who = writer()
who("Bond")
'Mr Bond'
那么 lambda 接受位置参数 x 对吗?通过将函数对象 writer() 分配给“谁”,我可以以某种方式访问 lambda 吗?
最佳答案
您正在返回一个函数,外部函数通过使用 __closure__
方法创建闭包而关闭,因此仍然存在对 title
的引用,因此可以在内部函数:
def writer():
title = "Mr"
name = (lambda x: title + ' ' + x)
return name
wr = writer()
print(wr.__closure__)
print(wr("foo"))
def writer():
title = "Mr"
def name(x):
return title + ' ' + x
return name
wr = writer()
print(wr.__closure__)
print(wr("foo"))
(<cell at 0x7eff4b221588: str object at 0x7eff4b11a500>,)
Mr foo
(<cell at 0x7eff49883108: str object at 0x7eff4b11a500>,)
Mr foo
如果您采用以下函数工厂,该函数工厂接受输入 e
(您希望在内部函数中将 x
提升为指数):
def exp(e):
def rse_to(x):
return x ** e
return rse_to
square = exp(2)
print(square(2)) # call inner function, returns 2 ** 2
在您的第一个函数中,您不接受任何参数,因此无法传递任何参数。您只需返回带有一个位置参数的 lambda 函数。
def writer():
title = "Mr"
name = (lambda x: title + ' ' + x)
return name
wr = writer()
print(wr)
<function writer.<locals>.<lambda> at 0x7f60e699dbf8>
您尝试通过向 writer 传递 arg 来执行的操作与定义一个不带参数并尝试向其传递一个参数的普通函数没有什么不同。
In [2]: def foo():
...: print("I take no args")
...:
In [3]: foo()
I take no args
In [4]: foo(2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-3ab2f4e33a15> in <module>()
----> 1 foo(2)
TypeError: foo() takes 0 positional arguments but 1 was given
关于Python def 函数使用 lambda 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28900851/