我有两个文件:
file1:
import file2
file2.func1(file2.variable1)
def func2(arg):
print('this is func2')
print('it takes this:', arg)file2:
import file1
variable1 = 'this is variable 1'
def func1(var):
print('this is function1')
print('and', var)
file1.func2(variable1)我想要这样拆分的主要原因是我的项目变得非常大,我想开始将一些函数移动到单独的.py文件中,以便更好地阅读和更舒适地维护。Pycharm IDE没有拾取任何错误,但当我运行它时,我得到:
AttributeError: module 'file1' has no attribute 'func2'扩展函数的最佳实践是什么?
发布于 2021-02-05 09:16:58
我不会使用循环导入。尝试如下设置:
modules的package,为空文件)statics和您的函数调用的导入)file1.py:
import statics
statics.func1(statics.variable1)file2.py:
import statics
statics.func2(statics.variable1)statics.py:
variable1 = 'this is variable 1'
def func2(arg):
print('this is func2')
print('it takes this:', arg)
def func1(var):
print('this is function1')
print('and', var)这解决了循环导入问题,并为您节省了吨的麻烦:)
发布于 2021-02-05 09:17:11
在python中使用打包是一个很好的实践。您正在尝试将文件相互导入。这称为循环依赖。尝试在一个包中创建所有实用程序,然后导入到另一个包中。它应该是单向的。
下面是一个示例:

https://stackoverflow.com/questions/66055961
复制相似问题