导入时发生了什么?

时间:2019-06-26 02:55:58

标签: python

我尝试处理循环导入,代码如下

logs.py

from settings import setting

def _print():
    if setting.is_print:
        print('yes')
    else:
        print('no')

setttings.py

from logs import _print


class Setting:
    def __init__(self):
        self.is_print = True

    @staticmethod
    def print_exception():
        return _print()


setting = Setting()

if __name__ == '__main__':
    setting.print_exception()

当我执行settings.py时,输出如下

ImportError: cannot import name '_print'

我尝试如下更改文件settings.py

try:
    from logs import _print
except ImportError:
    pass

class Setting:
    def __init__(self):
        self.is_print = True

    @staticmethod
    def print_exception():
        return _print()


setting = Setting()

if __name__ == '__main__':
    setting.print_exception()

更改setting.py后运行时的输出

yes

我不知道发生了什么

1 个答案:

答案 0 :(得分:0)

try:
    from logs import _print
except ImportError:
    pass

此块确保没有导入循环,因此代码可以正常执行。