我有3个文件如下:
1)main.py:
from global_file import globalClass,evalCodeClass,execCodeClass
from sub_file import makeClassInstances
if __name__ == "__main__":
globalClassInstance = makeClassInstances()
print "In Main: globalClassInstance.name=",globalClassInstance.name
print "In Main: globalClassInstance.classVar=",globalClassInstance.classVar
print "In Main: globalClassInstance.classInstances['B']=",globalClassInstance.classInstances['B']
globalClassInstance.classInstances['B'].run()
2)global_file.py:
global globalClassInstance
class globalClass():
def __init__(self):
self.classVar = None
self.name = 'howdy'
self.classInstances = {}
class evalCodeClass():
def __init__(self,name=None):
self.code = "globalClassInstance.classVar"
def run(self,caller=None):
exec self.code in globals()
class execCodeClass():
def __init__(self,name=None):
self.code = "globalClassInstance.classVar='hello'"
def run(self,caller=None):
exec self.code in globals()
3)sub_file.py:
from global_file import globalClass,evalCodeClass,execCodeClass
def makeClassInstances():
globalClassInstance = globalClass()
print globalClassInstance.name
evalCodeInstance = evalCodeClass('A')
execCodeInstance = execCodeClass('B')
globalClassInstance.classInstances['A'] = evalCodeInstance
globalClassInstance.classInstances['B'] = execCodeInstance
return globalClassInstance
我希望能够使用exec
和eval
函数来设置实例globalClassInstance
类变量classVar
,但它似乎是{{1}当这些文件被分隔在这样的文件中时,找不到它们。
我得到以下内容:
globalClassInstance
当代码全部在一个文件中时,这可以正常工作。我在使用global关键字时尝试了很多变体,仍然无法在其他类实例中获取eval或exec代码以找出如何引用howdy
In Main: globalClassInstance.name= howdy
In Main: globalClassInstance.classVar= None
In Main: globalClassInstance.classInstances['B']= <global_file.execCodeClass instance at 0x03131D00>
Traceback (most recent call last):
File "C:\Users\shinn\Documents\python\NLTK\StateMachine\New folder\main_file.py", line 9, in <module>
globalClassInstance.classInstances['B'].run()
File "C:\Users\shinn\Documents\python\NLTK\StateMachine\New folder\global_file.py", line 20, in run
exec self.code in globals()
File "<string>", line 1, in <module>
NameError: name 'globalClassInstance' is not defined
>>>
。
非常感谢您的帮助 - 我确定我只是个白痴; - )