“库”文件中的python eval

时间:2015-08-19 18:41:36

标签: python python-2.7

如果我有档案,我们会称他为 test1.py ,其中包含:

code='''
class Something(object):
  def __init__(self):
    print "blah blah blah, this is a horrible idea"
def run():
  print "don't preach at me you pretentious fool"
'''
eval(compile(code, '<string>', 'exec')) 

然后低于我的eval声明,在相同的 test1.py 文件中,我当然可以执行以下操作:

x = Something()
run()

但是...如果说我有另一个名为 test2.py 的文件,我希望能够运行run()或从那里实例化Something在发射import test1之后?我假设有一些必要的操作locals()globals(),但谷歌在这里让我失望。

1 个答案:

答案 0 :(得分:2)

不,我认为您不需要执行任何类型的locals()globals()操作,您可以执行 - import test1,然后将Something对象实例化为 -

import test1
x = test1.Something()
test1.run()

示例/演示 -

我的a.py与您为test1.py粘贴的代码完全相同,然后我就可以了 -

>>> import a
>>> x = a.Something()
blah blah blah, this is a horrible idea
>>> a.run()
don't preach at me you pretentious fool

另外,你应该听听__init__()所说的内容,这真是一个可怕的主意。