Analyze and solve problems python import error cycle

Analyze and solve problems python import error cycle

First, the cause of introduction cycle
#m1
from m2 import y
x=1

#m2
from m1 import x
y=10

原因:因为python解释器是从上往下解释,在执行from命令之前还没有加载x , y,所以当执行m1文件的时候,找到不y,x
Second, the solution
1, a first embodiment
#m1
x=1
from m2 import y
print(x)
print(y)
#m2
y=10
from m1 import x

执行m1结果:
        1
        10
        1
        10
        
The second method
#m1
def foo():
    from m2 import y
    print(y)
x=1
foo()

#m2
def boo():
    from m1 import x
    print(x)
y=10
boo()

执行m1函数:
    10
    1
    10
The third method (solution print duplicates)
#m1
def foo():
    from m2 import y
    print(y)
x=1
if __name__=="__main__"
    foo()

#m2
def boo():
    from m1 import x
    print(x)
y=10
boo()
执行m1文件结果:
    1
    10
to sum up:

The reason is because of the emergence of circulating import custom file import cycle, during the import, the variable need not be loaded, so we will be able to use the file where, on where to import the module, and import the module into the function in

Guess you like

Origin www.cnblogs.com/chuwanliu/p/10980457.html