python成功导入模块却不能正常使用

在正常使用python代码的时候,我们99%都会导入模块。
有一种情况:导入模块在ide上显示没有问题,但在使用的时候就会出现问题

code如下:

A.py

import B

class A_Class:
    def __init__(self):
        print('a_class init the code')

    def testA(self):
        print('执行testA')

B.py

import A
class B_Class:
    def __init__(self):
        print('b_class init the code')

    def testB(self):
        A.A_Class()
        print('执行testB')

b = B_Class()
b.testB()

如果我直接运行B模块,那么会出现如下报错信息:

b_class init the code
Traceback (most recent call last):
  File "/home/liudong/Desktop/test/B.py", line 1, in <module>
    import A
  File "/home/liudong/Desktop/test/A.py", line 1, in <module>
    import B
  File "/home/liudong/Desktop/test/B.py", line 11, in <module>
    b.testB()
  File "/home/liudong/Desktop/test/B.py", line 7, in testB
    A.A_Class()
AttributeError: module 'A' has no attribute 'A_Class'

这个问题的产生在于A.py文件,其中A文件中导入了B模块,如此产生了循环依赖,导致python代码出现问题,我们只需要将 A.py中的导入语句注释掉即可成功运行。
在这里插入图片描述

在这里插入图片描述

发布了22 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_38727626/article/details/88175025
今日推荐