我是一位经验丰富的 C# 开发人员,但最近不得不编写一些 python 代码。我真的很喜欢这种语言,但我正在努力将我的一些代码拆分成模块。为简单起见,我基本上有 2 个模块,第一个模块如下所示:文件1.pyfrom file2 import addOperation, volumeOperationclass 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()文件2.pyclass addOperation: def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def calculate(self): return self.num1 + self.num2class 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__.pyimport file1, file2这 3 个文件位于一个名为“mylibrary”的文件夹中,当我运行“python .\file1.py”时,一切都按预期工作。然后使用这个 setup.py 将该模块构建到一个轮子中:import setuptoolsprint(setuptools.find_packages())setuptools.setup( name="mylibrary", version="1.0.0", author="me", author_email="me@me.com", 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.file1if __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 问题,但我无法让它工作。我应该修改什么才能使其工作?
添加回答
举报
0/150
提交
取消