Lambdas,可调用类实例和范围;为什么它不适用于Python 2.7?

时间:2012-11-03 19:32:14

标签: python lambda python-2.7 scope

有人可以向我解释为什么以下代码会产生异常吗?

>>> class CallableKlass(object):
    def __init__(self, callible):
        self.callible = callible
    def __call__(self, arg):
        return self.callible(arg)


>>> class Klass(object):
    d = {'foo': 'bar'}
    m = CallableKlass(lambda x: d[x])


>>> Klass.m('foo')

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    Klass.m('foo')
  File "<pyshell#5>", line 5, in __call__
    return self.callible(arg)
  File "<pyshell#9>", line 3, in <lambda>
    m = CallableKlass(lambda x: d[x])
NameError: global name 'd' is not defined

2 个答案:

答案 0 :(得分:3)

无法从该命名空间中定义的函数中访问类命名空间(直接在类主体中定义的东西)。 lambda只是一个函数,所以这也适用于lambdas。你的CallableKlass是一只红鲱鱼。在这个更简单的情况下,行为是相同的:

>>> class Foo(object):
...     d = {'foo': 'bar'}
...     (lambda stuff: d[stuff])('foo')
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    class Foo(object):
  File "<pyshell#3>", line 3, in Foo
    (lambda stuff: d[stuff])('foo')
  File "<pyshell#3>", line 3, in <lambda>
    (lambda stuff: d[stuff])('foo')
NameError: global name 'd' is not defined
>>> class Foo(object):
...     d = {'foo': 'bar'}
...     def f(stuff):
...         d[stuff]
...     f('foo')
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    class Foo(object):
  File "<pyshell#4>", line 5, in Foo
    f('foo')
  File "<pyshell#4>", line 4, in f
    d[stuff]
NameError: global name 'd' is not defined

答案 1 :(得分:2)

你应该在lambda中使用Klass.d,因为在类中声明的变量成为该类的属性。 这就是你的程序引发错误的原因,因为它无法在全局变量中找到类似d的内容。:

class Klass(object):
    d = {'foo': 'bar'}
    m = CallableKlass(lambda x: Klass.d[x])