4

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

>>> 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
4

2 回答 2

3

类命名空间(直接在类主体中定义的东西)不能从该命名空间中定义的函数中访问。lambda 只是一个函数,因此这也适用于 lambda。你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
于 2012-11-03T19:38:12.893 回答
2

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

class Klass(object):
    d = {'foo': 'bar'}
    m = CallableKlass(lambda x: Klass.d[x])
于 2012-11-03T19:35:04.923 回答