使用lambda进行Python def函数赋值

时间:2015-03-06 14:26:41

标签: python lambda variable-assignment function

这是如何运作的:

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()分配给'who'我以某种方式可以访问lambda?

1 个答案:

答案 0 :(得分:2)

您正在返回一个函数,外部函数将关闭使用__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>

通过将arg传递给writer,你要做的就是定义一个没有args并试图传递给它的普通函数。

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