what is __init__.py for?

本文详细介绍了Python中两种类型的包:常规包和命名空间包。常规包作为目录包含__init__.py文件,当导入包时,此文件会被隐式执行。Python在导入模块时会搜索一系列目录,包括当前目录、PYTHONPATH环境变量指定的目录和安装依赖默认路径。文章还解释了如何通过修改sys.path来改变搜索路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python defines two types of packages. regular packages and namespace packages. Regular packages are traditional packages as they existed in python3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package's namespace. The __init__.py file can contain the same python code that any other module can contain, and python will add some additional features to the module when it is imported.

 

python searches a list of directories to resolve names in e.g., import statements. Because these can be any direcotry, and arbitary ones can be added by the end user, the developers have to worry about directories that happen to share a name with a valid python module, such as string in the docs example. To alleviate this, it ignores directories which do not contain a file named __init__.py, even if it is blank.

 

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.pathsys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).

  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值