首页 > 解决方案 > 为什么列表/字典理解在类中具有不同的范围?

问题描述

执行失败:

class Data:
    foo = 12
    bar = 42
    baz = [i * bar for i in range(foo)]

执行此工作:

foo = 12
bar = 42
baz = [i * bar for i in range(foo)]

我发现这个问题似乎是本质上相同问题的更复杂版本,但没有明确答案为什么范围似乎在类 + dict / 列表理解中发生变化。

标签: pythonscopelist-comprehensiondictionary-comprehension

解决方案


推荐阅读