Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'module' object has no attribute

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:

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.

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.

Any help is appreciated!

like image 581
gearhead Avatar asked Apr 19 '13 16:04

gearhead


People also ask

Why am I getting AttributeError object has no attribute?

If you are getting an object that has no attribute error then the reason behind it is because your indentation is goofed, and you've mixed tabs and spaces.

How do you fix an object that has no attribute?

In the example above, object b has the attribute disp , so the hasattr() function returns True. The list doesn't have an attribute size , so it returns False. If we want an attribute to return a default value, we can use the setattr() function. This function is used to create any missing attribute with the given value.

How do I fix AttributeError in Python?

Solution for AttributeError Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised.


1 Answers

I think you're right and it's an import issue. The matplotlib module doesn't have a figure function:

>>> 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:

>>> 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.)

like image 82
DSM Avatar answered Sep 20 '22 13:09

DSM