全局初始化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!! 中使用其中一个的实例! 我可以这样做吗?
编辑:
我想访问 new.py 中 test.py 中的变量来执行一些处理并将它们返回给 test.py。这不可能吗?
I have two files, one of the test.py is
import new.py
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
one.run()
and new.py
class New:
def __init__(self):
one.run()
New()
Now when i run python test.py I get this error,
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
But I want to use this instance of one in my New!!
Can I do this??
edit:
I want to access the variable in test.py in new.py to do some process and give them back to test.py. Isn't this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望
New
类使用您创建的Test
实例,则必须将其作为构造函数的一部分传递。new.py
test.py
使用全局变量是一种很好的方法,可以在不知道自己是如何做到的情况下破坏代码。最好显式传递您要使用的引用。
If you want your
New
class to use the instance ofTest
you created, you have to pass it in as part of the constructor.new.py
test.py
Playing around with globals is a great way to break your code without realizing how you did it. It is better to explicitly pass in the reference you want to use.
不,你不能。您能得到的最接近的是将您需要的东西传递给构造函数:
No, you can't. The closest you can get is to pass the thing you need in to the constructor:
one
定义在if __name__=='__main__'
块内。因此,仅当
test.py
作为脚本运行(而不是导入)时,one
才会被定义。为了让模块
new
从test
模块访问one
,您需要将one
从if __name__
block:test.py:
然后通过限定名称
test.one
访问one
:新.py:
one
is defined inside theif __name__=='__main__'
block.Consequently,
one
will get defined only iftest.py
is run as a script (rather than imported).For the module
new
to accessone
from thetest
module, you'll need to pullone
out of theif __name__
block:test.py:
Then access
one
by the qualified nametest.one
:new.py: