Python 在模块上调用dir函数

Python 在模块上调用dir函数,python,python-2.7,Python,Python 2.7,当我用dir查找bolton中的方法列表时,我得到了以下输出 >>> import boltons >>> dir(boltons) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] 当我明确地说 >>> from boltons.strutils import camel2under >>> dir(boltons

当我用dir查找bolton中的方法列表时,我得到了以下输出

>>> import boltons
>>> dir(boltons)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
当我明确地说

>>> from boltons.strutils import camel2under
>>> dir(boltons)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'strutils']
发现strutils被添加到Bolton的属性中

为什么在显式导入之前,strutils不显示?

从中了解dir的作用:

使用参数,尝试返回的有效属性列表 那个物体

导入boltons包时,我们可以看到strutils不是boltons对象上的属性。因此,我们不希望它出现在
dir(boltons)

关于导入子模块的说明如下:

例如,如果程序包spam具有子模块foo,则导入spam.foo后,spam将具有绑定到子模块的属性foo

导入子模块将在包上创建属性。在您的示例中:

>>>import boltons
>>>getattr(boltons, 'strutils')
AttributeError: module 'boltons' has no attribute 'strutils'
>>>from boltons.strutils import camel2under
>>>getattr(boltons, 'strutils')
<module 'boltons.strutils' from '/usr/local/lib/python3.5/site-packages/boltons/strutils.py'>
导入博尔顿 >>>getattr(博尔顿语,“strutils”) AttributeError:模块“boltons”没有属性“strutils” >>>从boltons.strutils进口camel2under >>>getattr(博尔顿语,“strutils”) 因此,在这种情况下,我们确实希望strutil出现在
dir(boltons)

>>>import boltons
>>>getattr(boltons, 'strutils')
AttributeError: module 'boltons' has no attribute 'strutils'
>>>from boltons.strutils import camel2under
>>>getattr(boltons, 'strutils')
<module 'boltons.strutils' from '/usr/local/lib/python3.5/site-packages/boltons/strutils.py'>