我有2个脚本,并且都需要使用在另一个脚本上定义的函数。我想做这样的事情:
file1.py:
from file2 import function2
def function1():
someCode...
... some code where I use function2...
file2.py:
from file1 import function1
def function2():
someCode...
... some code where I use funcion1 ...
问题是它不起作用,我不知道为什么也不知道如何修复它。我该怎么做?
选项#1移动函数1和function2到公共文件:
common.py
:
def function1():
# some stuff
pass
def function2():
# some stuff
pass
和incount function1 and function2来自CONCOL。
选项#2使用本地import
:
def function1():
someCode...
def some_method_where_function_2_is_used():
from .file2 import function2
... some code where I use function2...
问题是从其他文件运行该函数的代码在导入上运行,因此您最终以无尽的周期不喜欢。
修复,也许在两个单独的.py
S中运行功能,然后在另外两个中定义它们。
将'常规'函数分为'常规'模块以绕过副作用。
file1.py:
from utils import function1
file2.py:
from utils import function2
utils.py:
def function1():
pass
def function2():
pass
在文件所在的目录中创建一个空的__init__.py
文件。这将以包装的价格将其初始化,并允许您导入内部的文件。