python 包必须存在init_python3.6 中__init__.py对于一个包来说是否是必须的?

__init__.py 文件是Python将目录视为包的标志,它作为包的初始化入口。在Python3中,虽然命名空间包不需要__init__.py,但常规包仍然需要这个文件。在导入时,如果找不到__init__.py,Python会查找模块或创建命名空间包。一旦创建,无论是常规包还是命名空间包,它们在功能上没有区别。
摘要由CSDN通过智能技术生成

如果不添加__init__ python不会将其视作包,这个是包的初始化入口,当你第一次import该包时,会运行__init__。该包的__file__属性会指向__init__所在路径。

你这里说的没有__init__的是python3的新feature:命名空间包。这么写在python2中是报错的。

print(subdir2.__path__)

print(subdir2.__path__)

你可以看看区别。

Regular packages will continue to have an __init__.py and will reside in a single directory.

Namespace packages cannot contain an __init__.py. As a consequence, pkgutil.extend_path and pkg_resources.declare_namespace become obsolete for purposes of namespace package creation. There will be no marker file or directory for specifying a namespace package.

During import processing, the import machinery will continue to iterate over each directory in the parent path as it does in Python 3.2. While looking for a module or package named "foo", for each directory in the parent path:

If /foo/__init__.py is found, a regular package is imported and returned.

If not, but /foo.{py,pyc,so,pyd} is found, a module is imported and returned. The exact list of extension varies by platform and whether the -O flag is specified. The list here is representative.

If not, but /foo is found and is a directory, it is recorded and the scan continues with the next directory in the parent path.

Otherwise the scan continues with the next directory in the parent path.

If the scan completes without returning a module or package, and at least one directory was recorded, then a namespace package is created. The new namespace package:

Has a __path__ attribute set to an iterable of the path strings that were found and recorded during the scan.

Does not have a __file__ attribute.

Note that if "import foo" is executed and "foo" is found as a namespace package (using the above rules), then "foo" is immediately created as a package. The creation of the namespace package is not deferred until a sub-level import occurs.

A namespace package is not fundamentally different from a regular package. It is just a different way of creating packages. Once a namespace package is created, there is no functional difference between it and a regular package.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值