Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 Python循环相对导入在Python 3中工作,但在Python 2中不工作_Python 2.7_Python 3.x_Import_Circular Dependency - Fatal编程技术网

Python 2.7 Python循环相对导入在Python 3中工作,但在Python 2中不工作

Python 2.7 Python循环相对导入在Python 3中工作,但在Python 2中不工作,python-2.7,python-3.x,import,circular-dependency,Python 2.7,Python 3.x,Import,Circular Dependency,这在Python3中起作用,但在Python2(版本2.7)中会发出一个警告: Shell命令: $> python main.py main.py import mymodule mymodule.KlassX().talk_klass_y() mymodule.KlassY().talk_klass_x() mymodule/\uuuuu init\uuuuuu.py from .x import KlassX from .y import KlassY mymodule/x.

这在Python3中起作用,但在Python2(版本2.7)中会发出一个警告:

Shell命令:

$> python main.py
main.py

import mymodule

mymodule.KlassX().talk_klass_y()
mymodule.KlassY().talk_klass_x()
mymodule/\uuuuu init\uuuuuu.py

from .x import KlassX
from .y import KlassY
mymodule/x.py

from . import y  # circular import

def KlassX:
    def talk(self):
        print('Im in KlassX')

    def talk_klass_y(self):
        y.KlassY().talk()
mymodule/y.py

from . import x  # circular import

def KlassY:
    def talk(self):
        print('Im in KlassY')

    def talk_klass_x(self):
        x.KlassX().talk()
正如您可能已经注意到的,我已经将循环导入编写为相对导入,因为对于包()中的导入,建议这样做

我还尝试了绝对进口:

from mymodule import y  # in mymodule/x.py
from mymodule import x  # in mymodule/y.py
但这只适用于Python3,而不适用于Python2(因为同样的原因)

在python 2中使其工作的唯一方法是使用带有以下未推荐符号的相对导入:

import y  # in mymodule/x.py
import x  # in mymodule/y.py
我真的不喜欢它,因为“importsomemodule”作为相对导入只在Python2中有效,因为在Python3中它总是被强制为绝对导入。 我不明白为什么这个符号:

from mymodule import x
# or
from . import x
在Python2和Python3中都被接受,它们的行为不同

有线索吗?
我应该如何正确地在python 2中执行循环导入?

看一下简短的摘要:

我明白了!问题在于Python2没有按预期工作,因此我必须坚持使用
importX
。。。