Why am I getting AttributeError: Object has no attribute?

PythonPython MultithreadingAttributeerror

Python Problem Overview


I have a class MyThread. In that, I have a method sample. I am trying to run it from within the same object context. Please have a look at the code:

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter, redisOpsObj):
		threading.Thread.__init__(self)
		self.threadID = threadID
		self.name = name
		self.counter = counter
		self.redisOpsObj = redisOpsObj
		
	def stop(self):
		self.kill_received = True
			
	def sample(self):
		print "Hello"
				
	def run(self):
		time.sleep(0.1)
		print "\n Starting " + self.name
		self.sample()

Looks very simple ain't it. But when I run it I get this error

AttributeError: 'myThread' object has no attribute 'sample' Now I have that method, right there. So what's wrong? Please help

Edit: This is the stack trace

Starting Thread-0

Starting Thread-1
Exception in thread Thread-0:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "./redisQueueProcessor.py", line 51, in run
self.sample()
AttributeError: 'myThread' object has no attribute 'sample'

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "./redisQueueProcessor.py", line 51, in run
self.sample()
AttributeError: 'myThread' object has no attribute 'sample'

I am calling it like this

arThreads = []
maxThreads = 2;

for i in range( maxThreads ):
    redisOpsObj = redisOps()
    arThreads.append( myThread(i, "Thread-"+str(i), 10, redisOpsObj) )

Sorry, I can't post the redisOps class code. But I can assure you that it works just fine

Python Solutions


Solution 1 - Python

Your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.

Solution 2 - Python

If you’re using python 3+ this may also occur if you’re using private variables that start with double underscore, e.g., self.__yourvariable. Just something to take note of for some of you who may run into this issue.

Solution 3 - Python

These kind of bugs are common when Python multi-threading. What happens is that, on interpreter tear-down, the relevant module (myThread in this case) goes through a sort-of del myThread.

The call self.sample() is roughly equivalent to myThread.__dict__["sample"](self). But if we're during the interpreter's tear-down sequence, then its own dictionary of known types might've already had myThread deleted, and now it's basically a NoneType - and has no 'sample' attribute.

Solution 4 - Python

This may also occur if your using slots in class and have not added this new attribute in slots yet.

class xyz(object):
"""
class description

"""

__slots__ = ['abc', 'ijk']

def __init__(self):
   self.abc = 1
   self.ijk = 2
   self.pqr = 6 # This will throw error 'AttributeError: <name_of_class_object> object has no attribute 'pqr'

Solution 5 - Python

Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName.

Solution 6 - Python

I got this error for multi-threading scenario (specifically when dealing with ZMQ). It turned out that socket was still being connected on one thread while another thread already started sending data. The events that occured due to another thread tried to access variables that weren't created yet. If your scenario involves multi-threading and if things work if you add bit of delay then you might have similar issue.

Solution 7 - Python

The same error occurred when I had another variable named mythread. That variable overwrote this and that's why I got error

Solution 8 - Python

I have encountered the same error as well. I am sure my indentation did not have any problem. Only restarting the python sell solved the problem.

Solution 9 - Python

You can't access outside private fields of a class. private fields are starting with __ . for example -

class car:
    def __init__(self):
        self.__updatesoftware()
        
    def drive(self):
        print("driving")
    
    def __updatesoftware(self):
        print("updating software:")
        
obj = car()
obj.drive()  
obj.__updatesoftware()  ## here it will throw an error because 

__updatesoftware is an private method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShades88View Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonTimothy MugayiView Answer on Stackoverflow
Solution 3 - PythonTrevor View Answer on Stackoverflow
Solution 4 - PythonMitendraView Answer on Stackoverflow
Solution 5 - PythonShyam GuptaView Answer on Stackoverflow
Solution 6 - PythonShital ShahView Answer on Stackoverflow
Solution 7 - PythonremobobView Answer on Stackoverflow
Solution 8 - PythonMohammad SadoughiView Answer on Stackoverflow
Solution 9 - Pythonmukesh yadavView Answer on Stackoverflow