Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an AttributeError: <class> has no attribute <method>

I am creating a method in a class in a module mod1 and calling it as follows:

class blahblah:
   def foobar(self, bvar, **dvar)
       ////
       return dvar

And calling it as:

obj1 = mod1.blahblah()
dvar1 = obj1.foobar(True, **somedictionary)

It throws a Attribute error: blahblah has no attribute named foobar

Could you please help me with it? Thanks in advance

like image 299
nerdy_darkknight Avatar asked Oct 26 '12 21:10

nerdy_darkknight


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.

Can a class attribute can be used without an instance of that class?

while you can access class attributes using an instance it's not safe to do so. In python, the instance of a class is referred to by the keyword self. Using this keyword you can access not only all instance attributes but also the class attributes.

What does Object has no attribute mean in Python?

It's simply because there is no attribute with the name you called, for that Object. This means that you got the error when the "module" does not contain the method you are calling.

How does Python handle attribute errors?

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

The type of error you describe can be caused simply by mismatched indentation. If the method is at the very bottom of your class, move it up in the class a bit and the problem will become apparent.

When python interpreters run into mismatched indents (like say you started using tabs at the bottom of a file that was indented with spaces), the interpreter will not always throw an error; it can simply ignore the rest of the file. I ran into this just today while updating some old code where the original author used different whitespace chars (that happened to match my Geany tabs), and it threw me for a loop for a lot longer than I'd like to admit. :)

like image 131
3vi1 Avatar answered Sep 18 '22 13:09

3vi1