Dictionary class attribute that refers to other class attributes in the definition

孤人 提交于 2019-11-29 16:01:31
BrenBarn

Yes, it's because it's in a dictionary comprehension. Note that it's not "finding" UNKNOWN either; it's just not looking for it yet, because UNKNOWN is only referenced in a lambda. If you replace your dict comprehension with something else to allow the class definition to succeed, you'll get an error later if you try to access a nonexistent key (because then it will try to call that lambda). So if you change it to

FAVES = defaultdict(lambda: UNKNOWN, {'a': 1})

You'll get:

>>> OurFavAnimals.FAVES['x']
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    OurFavAnimals.FAVES['x']
  File "<pyshell#2>", line 5, in <lambda>
    FAVES = defaultdict(lambda: UNKNOWN, {'a': 1})
NameError: global name 'UNKNOWN' is not defined

In both cases, the reason is that variables defined in the class scope are not available in nested scopes. In other words, it's the same reason this fails:

class Foo(object):
    something = "Hello"
    def meth(self):
        print(something)

Both the lambda and the dictionary comprehension create function scopes that are nested in the class scope, so they don't have access to the class variables directly. See also this related question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!