如何修复错误“AttributeError:'module'对象在python3中没有属性'client'?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25278607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:00:17  来源:igfitidea点击:

How to fix error "AttributeError: 'module' object has no attribute 'client' in python3?

pythonhttp

提问by tianzhi0549

The following is my code.

以下是我的代码。

import http
h1 = http.client.HTTPConnection('www.bing.com')

I think it's ok.But python give me the following error:

我认为没关系。但是python给了我以下错误:

AttributeError: 'module' object has no attribute 'client'.

AttributeError: 'module' 对象没有属性 'client'。

I wanted to know why and how to fix it.Thanks.

我想知道为什么以及如何解决它。谢谢。

采纳答案by abarnert

First, importing a package doesn't automatically import all of its submodules.*

首先,导入包不会自动导入其所有子模块。*

So try this:

所以试试这个:

import http.client


If that doesn't work, then most likely you've got a file named http.py, or a directory named http, somewhere else on your sys.path(most likely the current directory). You can check that pretty easily:

如果这不起作用,那么很可能您有一个名为 的文件http.py,或名为 的目录http,位于您的其他位置sys.path(很可能是当前目录)。你可以很容易地检查:

import http
http.__file__

That should give some directory like /usr/lib/python3.3/http/__init__.pyor /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/__init__.pyor something else that looks obviously system-y and stdlib-y; if you instead get /home/me/src/myproject/http.py, this is your problem. Fix it by renaming your module so it doesn't have the same name as a stdlib module you want to use.

那应该给出一些类似/usr/lib/python3.3/http/__init__.py/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/__init__.py其他看起来很明显 system-y 和 stdlib-y 的目录;如果您改为 get /home/me/src/myproject/http.py,这是您的问题。通过重命名您的模块来修复它,使其与您要使用的 stdlib 模块不具有相同的名称。



If that's not the problem, then you may have a broken Python installation, or two Python installations that are confusing each other. The most common cause of this is that installing your second Python edited your PYTHONPATHenvironment variable, but your first Python is still the one that gets run when you just type python.

如果这不是问题,那么您可能有一个损坏的 Python 安装,或者两个相互混淆的 Python 安装。最常见的原因是安装你的第二个 Python 编辑了你的PYTHONPATH环境变量,但你的第一个 Python 仍然是当你输入python.



* But sometimes it does. It depends on the module. And sometimes you can't tell whether something is a package with non-module members (like http), or a module with submodules (os). Fortunately, it doesn't matter; it's always save to import os.pathor import http.client, whether it's necessary or not.

* 但有时确实如此。这取决于模块。有时您无法判断某个东西是具有非模块成员(如http)的包,还是具有子模块(os)的模块。幸运的是,这并不重要;无论是否有必要,它总是保存到import os.pathor import http.client