Tag: 列表 理解

从类定义中的列表理解访问类variables

如何从类定义中的列表理解中访问其他类variables? 以下Python 2中的工作,但在Python 3中失败: class Foo: x = 5 y = [x for i in range(1)] Python 3.2给出的错误: NameError: global name 'x' is not defined 尝试Foo.x也不起作用。 任何想法如何在Python 3中做到这一点? 一个更复杂的激励例子: from collections import namedtuple class StateDatabase: State = namedtuple('State', ['name', 'capital']) db = [State(*args) for args in [ ['Alabama', 'Montgomery'], ['Alaska', 'Juneau'], # … ]] 在这个例子中, […]