我是一位经验丰富的C#开发人员,但最近不得不编写一些python代码。我真的很喜欢这种语言,但是我正努力将一些代码拆分成模块。为简单起见,我基本上有2个模块,第一个模块如下所示:
file1.py
from file2 import addOperation, volumeOperation
class utils:
def add(self, num1, num2):
op = addOperation(num1, num2)
return op.calculate()
def volume(self, length, width, height):
op = volumeOperation(length, width, height)
return op.calculate()
def main():
util = utils()
print(f"Adding 2 and 3 produces { util.add(2, 3) }")
print(f"Volume of a 2x2x2 cube is { util.volume(2,2,2) }")
if __name__ == '__main__':
main()
file2.py
class addOperation:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def calculate(self):
return self.num1 + self.num2
class volumeOperation:
def __init__(self, length, width, height):
self.width = width
self.height = height
self.length = length
def calculate(self):
return self.width * self.height * self.length
_init__.py
import file1, file2
这三个文件位于一个名为“ mylibrary”的文件夹中,当我运行“ python。\ file1.py”时,一切正常。然后使用以下setup.py将模块内置到轮子中:
import setuptools
print(setuptools.find_packages())
setuptools.setup(
name="mylibrary",
version="1.0.0",
author="me",
author_email="[email protected]",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"Operating System :: OS Independent"
],
)
然后使用“ python -m pip install --user mylibrary-1.0.0-py3-none-any.whl”安装生成的车轮,该轮毂似乎工作正常。
我的第二个模块是以下文件“ consumer.py”:
import mylibrary.file1
if __name__ == '__main__':
util = mylibrary.file1.utils()
print(f"Adding 2 and 3 produces { util.add(2, 3) }")
print(f"Volume of a 2x2x2 cube is { util.volume(2,2,2) }")
当我尝试运行“ python。\ consumer.py”(我在使用python 3.7的Windows上,顺便说一句)时,我收到“ ModuleNotFoundError:没有名为'file2'的模块”。
我尝试了不同的导入方式,尝试__init__.py
在mylibrary模块中使用空值,并且阅读了其他一些至少有类似问题的stackoverflow问题,但我无法使其正常工作。
我应该对此做些什么修改?
在Python 3中,隐式相对导入已删除:
相对导入的唯一可接受语法是来自。[module]导入名称。所有导入表单均不以开头。被解释为绝对进口。(PEP 0328)
您的
from file2 import ...
在file1.py中是这样的隐式相对导入(即,它在Python 2中可以作为相对导入,但现在在Python 3中被视为绝对导入)。
因此,您需要将其更改为绝对导入:
from mylibrary.file2 import ...
或明确的相对导入(使用前导点):
from .file2 import ...
如果确实需要它们,则还需要将其中的导入转换__init__.py
为
from . import file1
from . import file2
除此之外,您的setuptools发行版似乎已正确布置,并且对我有用(不错的BTW示例!)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句