如何全局初始化Python类?
我有两个文件,一个是 test.py,内容是:
import new.py
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
one.run()
另一个是 new.py,内容是:
class New:
def __init__(self):
one.run()
New()
现在当我运行 python test.py 时,我遇到了这个错误:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import new.py
File "/home/phanindra/Desktop/new.py", line 5, in <module>
New()
File "/home/phanindra/Desktop/new.py", line 3, in __init__
one.run()
NameError: global name 'one' is not defined
但是我想在我的 new.py 中使用 test.py 里的这个实例!我可以这样做吗??
补充说明:
我想在 new.py 中访问 test.py 里的一个变量,进行一些处理,然后再把结果返回给 test.py。这可能吗?
3 个回答
-1
one
是在 if __name__=='__main__'
这个代码块里面定义的。也就是说,只有当你直接运行 test.py
这个文件的时候,one
才会被定义,而如果你只是把它当作一个模块导入到其他地方,就不会定义它。
如果你想让 new
模块能够使用 test
模块里的 one
,你需要把 one
移到 if __name__
这个代码块外面:
test.py:
class Test:
def __init__(self):
return
def run(self):
return 1
one=Test()
if __name__ == "__main__":
one.run()
然后可以通过带有模块名的方式来访问 one
,也就是 test.one
:
new.py:
import test
class New:
def __init__(self):
test.one.run()
New()
0
不,你不能这样做。你能做到的最接近的方式是把你需要的东西传递给构造函数:
class New(object):
def __init__(self, one):
one.run()
5
如果你想让你的 New
类使用你创建的 Test
实例,你需要在构造函数中把它传进去。
new.py
class New:
def __init__(self, one):
one.run()
test.py
import new
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
two = new.New(one);
随便玩弄全局变量可能会让你的代码出错,而你却不知道是怎么回事。最好是明确地把你想用的引用传进去。