Python AttributeError: 'module' 对象没有属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16109039/
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 21:47:22  来源:igfitidea点击:

AttributeError: 'module' object has no attribute

pythonpython-2.7

提问by gearhead

I have looked at other posts here on this topic and not found a clear answer, though I'm sure its something simple.

我已经查看了有关此主题的其他帖子,但没有找到明确的答案,尽管我确信它很简单。

My code has the following structure...

我的代码具有以下结构...

import matplotlib
...
...

class xyz:
    def function_A(self,...)
        ...
        ...
        fig1 = matplotlib.figure()
        ...
        ...

I am calling 'function_A' from an instance of 'xyz' and when I do I get the error message:

我正在从 'xyz' 的实例调用 'function_A',当我这样做时,我收到错误消息:

AttributeError: 'module' object has no attribute 'figure'

Based on the posts I have read it seems like a problem with the way I'm importing matplotlib, but I can't sort it out. I have tried importing it within the Function_A definition (I think that is bad form but I wanted to test it), but I still the the same error.

根据我读过的帖子,我导入 matplotlib 的方式似乎有问题,但我无法解决。我尝试在 Function_A 定义中导入它(我认为这是错误的形式,但我想测试它),但我仍然出现相同的错误。

I have used my 'function_A' code elsewhere with no problem, but it was just a function in a module, not a method in a class.

我在其他地方使用了我的“function_A”代码没有问题,但它只是模块中的一个函数,而不是类中的方法。

Any help is appreciated!

任何帮助表示赞赏!

采纳答案by DSM

I think you're right and it's an import issue. The matplotlibmodule doesn't havea figurefunction:

我认为你是对的,这是一个进口问题。该matplotlib模块不具有一个figure功能:

>>> import matplotlib
>>> matplotlib.figure
Traceback (most recent call last):
  File "<ipython-input-130-82eb15b3daba>", line 1, in <module>
    matplotlib.figure
AttributeError: 'module' object has no attribute 'figure'

The figure function is located deeper. There are a few ways to pull it in, but the usual import looks more like:

figure 函数位于更深的位置。有几种方法可以将其拉入,但通常的导入看起来更像是:

>>> import matplotlib.pyplot as plt
>>> plt.figure
<function figure at 0xb2041ec>

It's probably a good idea to stick to this custom, because it's used by the majority of examples you'll find on the Web, such as those in the matplotlib gallery. (The gallery is is still the first place I go to when I need to figure out how to do something: I find an image which looks like what I want, and then look at the code.)

坚持这种习惯可能是个好主意,因为您可以在 Web 上找到的大多数示例都使用它,例如matplotlib 库中的示例。(当我需要弄清楚如何做某事时,画廊仍然是我去的第一个地方:我找到一个看起来像我想要的图像,然后查看代码。)