简体   繁体   English

“as”子句如何影响 Python 中的“import”?

[英]How does "as" clause affect "import" in Python?

I thought that "as" clause just makes an alias of an imported module.我认为“as”子句只是作为导入模块的别名。 However, "import" fails with "as" clause in the following code.但是,在以下代码中,“import”失败并带有“as”子句。

import tensorflow.python.eager as eager

This statement raises the following error.此语句引发以下错误。

Traceback (most recent call last):
  File "/home/snippet/prof/importer.py", line 2, in <module>
    import tensorflow.python.eager as eager
AttributeError: module 'tensorflow' has no attribute 'python'

When I remove the "as" clause, the "import" successes.当我删除“as”子句时,“导入”成功。 How does "as" clause affect the success and failure of "import"? “as”子句如何影响“import”的成败?

from tensorflow.python import eager

imports the name " tensorflow.python " and then gets its attribute eager , whereas导入名称“ tensorflow.python ”,然后获取其属性eager ,而

import tensorflow.python.eager as eager

imports the name " tensorflow ", and in there tries to find the attribute python , and from that the attribute eager , which it should then put in your global namespace as eager .导入名称“ tensorflow ”,并在其中尝试找到属性python ,并从中找到属性eager ,然后它应该将其作为eager放入您的全局命名空间中。 And that's a huge difference, since there is no object python in tensorflow's __init__.py , which is what represents the tensorflow package when imported and which does not know about any subpackages that might exist.这是一个巨大的差异,因为在 tensorflow 的__init__.py没有对象python ,它代表了导入时的 tensorflow 包,它不知道可能存在的任何子包。 Therefore the error因此错误

AttributeError: module 'tensorflow' has no attribute 'python' AttributeError: 模块“tensorflow”没有属性“python”

You should not have ".eager" while importing to import "eager" as something.导入时不应该有“.eager”以将“eager”作为某种东西导入。

Try this, it will work fine:试试这个,它会正常工作:

from tensorflow.python import eager as eager

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM