导入语句后,包中的模块不可用

时间:2019-06-26 15:51:12

标签: python tensorflow

脚本:

import tensorflow.python
tensorflow.python

得出AttributeError

AttributeError: module 'tensorflow' has no attribute 'python'

这怎么可能发生? from tensorflow import pythonfrom tensorflow.python import keras一样正常工作。我以为自己了解Python导入机制的基础知识,但是我不了解在什么情况下import x.y会成功,但是没有在命名空间中添加x.y

1 个答案:

答案 0 :(得分:1)

如果您查看tensorflow/__init__.py,则会看到它在末尾显式删除了名称python

# These symbols appear because we import the python package which
# in turn imports from tensorflow.core and tensorflow.python. They
# must come from this module. So python adds these symbols for the
# resolution to succeed.
# pylint: disable=undefined-variable
del python
del core
# pylint: enable=undefined-variable

因此,tensorflow.python无法访问,因为模块对象python的属性tensorflow已被删除。不过,您仍然可以从此处导入内容:

from tensorflow.python import ops  # Works

如果您想专门访问tensorflow.python模块,则不能使用该名称,但是也可以将其导入另一个名称:

from tensorflow import python as tfpython
print(tfpython)
# <module 'tensorflow.python' from '...'>
相关问题