将Python项目扩展到多个文件(MWE)
我有两个文件: 文件1:将Python项目扩展到多个文件(MWE),python,function,Python,Function,我有两个文件: 文件1: import file2 file2.func1(file2.variable1) def func2(arg): print('this is func2') print('it takes this:', arg) 文件2: import file1 variable1 = 'this is variable 1' def func1(var): print('this is function1') print('and
import file2
file2.func1(file2.variable1)
def func2(arg):
print('this is func2')
print('it takes this:', arg)
文件2:
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'
扩展函数的最佳实践是什么?我不会使用循环导入。请尝试以下设置:
- __init_uuu.py(确保文件夹被视为带有
模块的
,是一个空文件)包
- file1.py(将仅包含导入
和函数调用)静态
- file2.py(将仅包含导入
和函数调用)静态
- py(statics.py)将保存函数本身和声明的变量
import statics
statics.func1(statics.variable1)
import statics
statics.func2(statics.variable1)
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)
file2.py:
import statics
statics.func1(statics.variable1)
import statics
statics.func2(statics.variable1)
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)
statics.py:
import statics
statics.func1(statics.variable1)
import statics
statics.func2(statics.variable1)
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)
这解决了循环导入问题,并将为您节省大量麻烦:)我不会使用循环导入。请尝试以下设置:
- __init_uuu.py(确保文件夹被视为带有
模块的
,是一个空文件)包
- file1.py(将仅包含导入
和函数调用)静态
- file2.py(将仅包含导入
和函数调用)静态
- py(statics.py)将保存函数本身和声明的变量
import statics
statics.func1(statics.variable1)
import statics
statics.func2(statics.variable1)
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)
file2.py:
import statics
statics.func1(statics.variable1)
import statics
statics.func2(statics.variable1)
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)
statics.py:
import statics
statics.func1(statics.variable1)
import statics
statics.func2(statics.variable1)
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)
这解决了循环导入问题,并将为您节省大量麻烦:)使用python打包是一个很好的实践。 您正在尝试将这些文件相互导入。这称为循环依赖。 尝试在一个包中创建所有实用程序并导入到另一个包中。它应该是单向的
以下是一个例子:
在python中使用打包是一个很好的实践。 您正在尝试将这些文件相互导入。这称为循环依赖。 尝试在一个包中创建所有实用程序并导入到另一个包中。它应该是单向的
以下是一个例子:
如果可以避免,最好不要使用循环引用。Python在这里比大多数语言都更宽容,但最好不要太宽容。如果可以避免的话,最好不要使用循环引用。Python在这里比大多数语言都更宽容,但最好不要太宽容。