“__package__"的目的是什么?Python中的属性? [英] What's the purpose of the "__package__" attribute in Python?

查看:59
本文介绍了“__package__"的目的是什么?Python中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道__package__ 到底是什么意思?没有在官方文档中找到任何解释,即使是在 SO 上.

All I want to know is what exactly does __package__ mean? Didn't find any explanation in the official doc, even on SO.

如果你能提供一些例子,我会很高兴.

If you could provide some examples I would be very happy.

推荐答案

参见 PEP366导入系统参考文档:

主要提议的更改是引入了新的模块级属性 __package__.当它存在时,相对导入将基于此属性而不是模块 __name__ 属性.

The major proposed change is the introduction of a new module level attribute, __package__. When it is present, relative imports will be based on this attribute rather than the module __name__ attribute.

  • 应该设置模块的 __package__ 属性.它的值必须是一个字符串,但它可以是与它的 __name__ 相同的值.如果该属性设置为 None 或缺失,导入系统将用更合适的值填充它.当模块是一个包时,它的 __package__ 值应该设置为它的 __name__.当模块不是包时,__package__ 应设置为空字符串,对于顶级模块,或者对于子模块,应设置为父包的名称.有关详细信息,请参阅 PEP 366.
  • The module’s __package__ attribute should be set. Its value must be a string, but it can be the same value as its __name__. If the attribute is set to None or is missing, the import system will fill it in with a more appropriate value. When the module is a package, its __package__ value should be set to its __name__. When the module is not a package, __package__ should be set to the empty string for top-level modules, or for submodules, to the parent package’s name. See PEP 366 for further details.

因此,对于位于 foo/bar/baz.py 中的模块,__name__ 设置为 foo.bar.baz,并且__package__ 设置为 foo.bar,而 foo/bar/__init__.py 将有 foo.bar 用于__name____package__ 属性.

So, for a module located in foo/bar/baz.py, __name__ is set to foo.bar.baz, and __package__ is set to foo.bar, while foo/bar/__init__.py will have foo.bar for both the __name__ and __package__ attributes.

这篇关于“__package__"的目的是什么?Python中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆