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

南楼画角 提交于 2019-12-20 03:14:49

问题


While there are numerous ways around this, because of a personality fault I can't let it go until I understand the nature of the failure.

Attempting:

class OurFavAnimals(object):
    FAVE = 'THATS ONE OF OUR FAVORITES'
    NOTFAVE = 'NAH WE DONT CARE FOR THAT ONE'
    UNKNOWN = 'WHAT?'
    FAVES = defaultdict(lambda: UNKNOWN, {x:FAVE for x in ['dog', 'cat']})
    FAVES['Crab'] = NOTFAVE 

Fails with:

      3     NOTFAVE = 'NAH WE DONT CARE FOR THAT ONE'
      4     UNKNOWN = 'WHAT?'
----> 5     FAVES = defaultdict(lambda: UNKNOWN, {x:FAVE for x in ['dog', 'cat']})
      6     FAVES['Crab'] = NOTFAVE

NameError: global name 'FAVE' is not defined

Why? Why can it find UNKNOWN but not FAVE? Is it because it's in a dictionary comprehension?


回答1:


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.



来源:https://stackoverflow.com/questions/32257783/dictionary-class-attribute-that-refers-to-other-class-attributes-in-the-definiti

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