如何从类定义中的列表理解中访问其他类变量?以下代码在python2中有效,但在python3中无效:
class Foo:
x = 5
y = [x for i in range(1)]
Python 3.2给出了以下错误:
NameError: global name 'x' is not defined
尝试Foo。X也不行。关于如何在python3中做到这一点,有什么想法吗?
一个稍微复杂一点的激励例子:
from collections import namedtuple
class StateDatabase:
State = namedtuple('State', ['name', 'capital'])
db = [State(*args) for args in [
['Alabama', 'Montgomery'],
['Alaska', 'Juneau'],
# ...
]]
在这个例子中,apply()本来是一个不错的解决方案,但不幸的是,它从Python 3中被删除了。