全局初始化python类?

pah*_*nin 0 python initialization class

我有两个文件,其中一个是test.py

import new.py

class Test:

    def __init__(self):
        return
    def run(self):
        return 1

if __name__ == "__main__":
    one=Test()
    one.run()
Run Code Online (Sandbox Code Playgroud)

和new.py

class New:
    def __init__(self):
        one.run()

New()
Run Code Online (Sandbox Code Playgroud)

现在当我运行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
Run Code Online (Sandbox Code Playgroud)

但是我想在我的新手中使用这个实例!我可以这样做吗?

编辑:

我想在new.py中访问test.py中的变量来执行某个过程并将它们返回给test.py. 这不可能吗?

unh*_*ler 5

如果你希望你New的类使用的实例Test创建,你必须在把它作为构造函数的一部分.

new.py

class New:
    def __init__(self, one):
        one.run()
Run Code Online (Sandbox Code Playgroud)

test.py

import new

class Test:
    def __init__(self):
        return
    def run(self):
        return 1


if __name__ == "__main__":
    one=Test()
    two = new.New(one);
Run Code Online (Sandbox Code Playgroud)

使用全局变量是打破代码的好方法,而不会意识到你是如何做到的.最好明确传入要使用的引用.