Python 3 中的相对导入:神秘的错误
在 Python 3 中,相对导入是从同一个模块中导入模块的便捷方法目录。然而,经常会出现意想不到的错误:
错误消息:
- ImportError:尝试在没有已知父包的情况下进行相对导入
- ModuleNotFoundError:没有名为“mymodule”的模块
- 系统错误:父模块“未加载”,无法执行相对导入
根本原因:
要理解这些错误,我们必须深入研究Python的模块导入机制。相对导入要求导入模块包含在包中。包是通过 __init__.py 文件标记为包的目录。
常见布局:
包通常具有以下结构:
main.py mypackage/ __init__.py mymodule.py myothermodule.py
示例代码:
- mymodule.py
# Exported function def as_int(a): return int(a) # Test function for module def _test(): assert as_int('1') == 1 if __name__ == '__main__': _test()
- myoth ermodule.py
# Exported function def add(a, b): return as_int(a) + as_int(b) # Test function for module def _test(): assert add('1', '1') == 2 if __name__ == '__main__': _test()
- main.py
from mypackage.myothermodule import add def main(): print(add('1', '1')) if __name__ == '__main__': main()
何时你运行 main.py 或 mypackage/mymodule.py,一切顺利。但是,由于相对导入,运行 mypackage/myothermodule.py 失败:
from .mymodule import as_int
解决方案:
正如 Guido van Rossum 所解释的,此失败是由于Python 将包内运行的脚本视为反模式。推荐的解决方案是避免相对导入并使用绝对导入:
from mypackage.mymodule import as_int
替代方法:
如果您仍然喜欢相对导入,则可以使用 - m 选项指定要导入的模块,但它可能很冗长且不方便:
python3 -m mypackage.myothermodule
另一个另一种方法是操作 PYTHONPATH 以包含包的父目录:
import sys import os SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) from mypackage.mymodule import as_int
以上是为什么 Python 3 中的相对导入会失败,如何修复它们?的详细内容。更多信息请关注PHP中文网其他相关文章!

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

ArraySaresificatificallyfasterthanlistsForoperationsBenefiting fromDirectMemoryAcccccccCesandFixed-Sizestructures.1)conscessingElements:arraysprovideconstant-timeaccessduetocontoconcotigunmorystorage.2)iteration:araysleveragececacelocality.3)

ArraySareBetterForlement-WiseOperationsDuetofasterAccessCessCessCessCessCessAndOptimizedImplementations.1)ArrayshaveContiguucuulmemoryfordirectAccesscess.2)列出sareflexible butslible dueTopotentEnallymideNamicizing.3)forlarargedAtaTasetsetsetsetsetsetsetsetsetsetsetlib

在NumPy中进行整个数组的数学运算可以通过向量化操作高效实现。 1)使用简单运算符如加法(arr 2)可对数组进行运算。 2)NumPy使用C语言底层库,提升了运算速度。 3)可以进行乘法、除法、指数等复杂运算。 4)需注意广播操作,确保数组形状兼容。 5)使用NumPy函数如np.sum()能显着提高性能。

在Python中,向列表插入元素有两种主要方法:1)使用insert(index,value)方法,可以在指定索引处插入元素,但在大列表开头插入效率低;2)使用append(value)方法,在列表末尾添加元素,效率高。对于大列表,建议使用append()或考虑使用deque或NumPy数组来优化性能。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver CS6
视觉化网页开发工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器