在类中使用execfile获取参数时出现问题

2024-04-20 04:23:55 发布

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

我有一个与this question中的第一个问题类似的问题,据我所知,这个问题没有得到解答。在

我有档案”配置.py“它包含许多要由类使用的参数(此配置.py但是,我无法通过execfile将它们传播到类中。在

在示例代码中:

class Class():
    def __init__(self):
        execfile("config.py")
        print x

# config.py
x = "foo"

>>> t = Class()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
NameError: global name 'x' is not defined

欢迎使用任何帮助,或从要在类中使用的文件中检索参数的任何更好的方法。在

非常感谢。在


Tags: 代码inpyconfig示例参数initstdin
2条回答

我不明白你想做什么(但我不喜欢,这只是我自己),但要解决你的问题,就做(用python2.6测试):

class Class():
    def __init__(self):
        execfile('config.py', locals())  # Not recommanded, maybe you want globals().
        print x

但是从doc

Note

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. execfile() cannot be used reliably to modify a function’s locals.

关于:

Any help welcome, or any better methods of retrieving parameters from a file to be used in a class.

您可以使用import。在

尽管将配置设置保存在Python文件中可能会比较方便,但我还是建议不要这样做。我真的不想让你这么做。任何东西都可以放在配置文件中,包括恶意代码。在

我将使用json模块或ConfigParser模块来保存我的配置。在

如果您在这两者之间选择有困难,我建议您使用json模块。Json是一种简单而灵活的结构化数据格式。在

相关问题 更多 >