Python在类级cod中的字典理解问题

2024-06-26 01:31:31 发布

您现在位置:Python中文网/ 问答频道 /正文

最小示例

class foo:
    loadings = dict(hi=1)
    if 'hi' in loadings:
        print(loadings['hi']) 
        # works
        print({e : loadings[e] for e in loadings})
        # NameError global name 'loadings' not defined

我也尝试过引用类名称空间,但这也不起作用

^{pr2}$

当然,这和预期的一样

class foo:
    loadings = dict(hi=1)
    if 'hi' in loadings:
        print(loadings['hi'])

print({e : foo.loadings[e] for e in foo.loadings})

我想知道为什么这个范围问题会发生,如果我想做一些疯狂的事情,了解最好的方法。我的感觉是第一个代码片段应该按原样工作,但当然不是这样。在

目标

我正在为一些csv/json文件创建一个DataManager类/模块以及封闭的数据库查询,这是我的程序和获取数据的一站式服务。其中有一些静态数据和一些动态数据,所以在同一个类中似乎大量使用了静态和非静态数据成员。虽然我知道这些可能是模块级变量,但我喜欢静态类数据成员的概念(可能是因为Java的偏见)。非常感谢任何帮助

我的解决方案(目前)

我最终展开列表理解以保持在类范围内,在上面它会变成这样

class foo:
    loadings = dict(hi=1)
    temp = dict()
    for e in loadings:
        temp[e] = loadings[e] # keep in mind this is a minimal example, I probably wouldn't do (just) this
    print(temp) # works
    del temp

它不漂亮,但现在还管用


Tags: 模块inforiffoo静态成员hi
1条回答
网友
1楼 · 发布于 2024-06-26 01:31:31

根据Name and Binding docs

The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope. This means that the following will fail:

class A:
    a = 42
    b = list(a + i for i in range(10))

有关详细信息,请参见this answer。在


在Python2中,可以使用列表理解,因为它们是在不使用函数作用域的情况下实现的:

dict([(e,loadings[e]) for e in loadings])

但是如果在Python3中运行,这个代码就会中断。所以这里有一个替代的解决方法,可以在Python2和Python3中工作:

^{pr2}$

相关问题 更多 >