Python中的新模块

2024-09-29 01:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python创建一个新模块。这是git链接:https://github.com/Sanmitha-Sadhishkumar/strman 在使用pip上传和安装该模块之后,我发现我可以访问该模块

import strman.strman as s
s.func_name

要对其进行哪些更改

import strman
strman.func_name

Tags: 模块pipnamehttpsimportgitgithubcom
2条回答

__init__.py文件中,您希望使用相对导入

from .strman import *

您有一个strman包(外部目录)和一个strman模块(文件)。这是一个非常普遍的模式。但是没有相对导入,您的__init__.py在层次结构中的导入深度不够

更一般地说,无论何时从项目中的同级模块导入,几乎都应该使用相对导入,因为它是显式的,并且避免了各种复杂情况,例如您案例中的示例

您必须将文件移动到主目录中。您的目录将如下所示

\myProject
    - init.py
    - strman.py
    - main.py # <  this would be the file your programming is

阅读有关docs中模块的更多信息

相关问题 更多 >