2023-08-31
简单记一下今天遇到了哪些类型的问题
python3-circular import: 🔗 [python - What happens when using mutual or circular (cyclic) imports? - Stack Overflow] https://stackoverflow.com/questions/744373/what-happens-when-using-mutual-or-circular-cyclic-imports ,最后解决的办法是把import的语句往下移,放在需要import的代码上面(而不是代码顶部)
2025-07-10
原本是打算花一点时间稍微学一下然后把这篇笔记发出来的,结果发现这个问题还挺麻烦
写了几个case对着看了老半天,眼睛都看花了,只贴代码截图和结果,懒得解释了(因为根本没有学明白,只能跟着运行结果一点一点推测可能的原因)
更恐怖的是下面的这些代码实际上通过在各个地方加print语句还能变得更复杂,但我及时收手不学了。
以下所有case都默认a.py和b.py在同一个文件夹下,然后分别运行python3 a.py和python3 b.py
case1

答案
运行a.py,打印:b_function
运行b.py,打印:a_function
case 2

答案
运行a.py:AttributeError: partially initialized module 'b' has no attribute 'b_function' (most likely due to a circular import)
运行b.py:AttributeError: partially initialized module 'a' has no attribute 'a_function' (most likely due to a circular import)
case3

答案
运行a.py:AttributeError: partially initialized module 'b' has no attribute 'b_function' (most likely due to a circular import)
运行b.py:
b_function
a_function
case 3.5
和上面的case 3本质相同,就是在b.py多了一行令人讨厌的print语句增加点难度

答案
运行a.py:AttributeError: partially initialized module 'b' has no attribute 'b_function' (most likely due to a circular import)
运行b.py:
after import
b_function
after import
a_function
case 4

答案
运行a.py:
b_function
a_function
b_function
运行b.py:
a_function
b_function
a_function