我是一名初学者,正在努力从另一个模块调用实例成员。我的代码很长,但我可以用这个片段重现这个问题:
mainmodule.py:
from othermodule import *
class Class2_in_main():
mystring = 'Initial Value'
print mystring
def change_string(self, NewStringValue):
self.mystring = NewStringValue
print self.mystring
def main():
MyObjectInstance = Class2_in_main()
Object2 = othermodule.Class_in_othermodule()
if __name__ == '__main__':
main()
othermodule.py:
from mainmodule import *
class Class_in_othermodule():
MyObjectInstance().change_string('New String Value!')
这是我的堆栈:
Initial Value
Traceback (most recent call last):
File "mainmodule.py", line 1, in <module>
from othermodule import *
File "C:\PythonScripts\StackOverflowExample\othermodule.py", line 3, in <module>
class Class_in_othermodule():
File "C:\PythonScripts\StackOverflowExample\othermodule.py", line 6, in Class_in_othermodule
MyObjectInstance().change_string('New String Value!')
NameError: name 'MyObjectInstance' is not defined
我使用Python 2.7。
有什么想法吗?我很抱歉格式不好,这是我的第一个问题,我无法弄清楚它是如何工作的!
更新:我能够让我的代码正常工作,但我想了解如何专门为我的实例调用“change_string”(称为MyObjectInstance),我怎么能这样做?这是我现在拥有的:
mainmodule.py:
import othermodule
class Class2_in_main():
mystring = 'Initial Value'
print mystring
def change_string(self, NewStringValue):
self.mystring = NewStringValue
print self.mystring
def main():
global MyObjectInstance
MyObjectInstance = Class2_in_main()
Object2 = othermodule.Class_in_othermodule()
if __name__ == '__main__':
main()
othermodule.py:
class Class_in_othermodule():
mainmodule.Class2_in_main().change_string('New String Value!')