I wrote a short example because I can't share my original codes.
I think the problem was caused by python itself.
Anyway, when I start a thread for a class, the program crashes if there are conditions. What is the reason? What is also the possible solution.
from threading import Thread
global dicta
dicta={"number":0,"name":"John","animal":"pig"}
class PigMan:
def __init__(self):
Thread(target= self.iAmFool).start()
def iAmFool(self):
if dicta["number"]==0:
print("It's work")
else:
print("Wtf")
PigMan()
I expected it to run smoothly, but this is the error:
Traceback (most recent call last):
File "C:/Users/Pig/Desktop/test.py", line 13, in <module>
PigMan()
File "C:/Users/Pig/Desktop/test.py", line 6, in __init__
Thread(target= self.iAmFool).start()
AttributeError: 'PigMan' object has no attribute 'iAmFool'
Your indentation is off. Python is whitespace-sensitive, thus the indentation of your code is critically important.
Reducing def iAmFool's indentation correctly creates it as part of the class PigMan, as opposed to trying to def it within __init__.
from threading import Thread
global dicta
dicta={"number":0,"name":"John","animal":"pig"}
class PigMan:
def __init__(self):
Thread(target= self.iAmFool).start()
def iAmFool(self):
if dicta["number"]==0:
print("It's work")
else:
print("Wtf")
PigMan()
Repl.it
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
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
Your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.
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.
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.
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'
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.
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName.
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.
The same error occurred when I had another variable named mythread. That variable overwrote this and that's why I got error
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
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
Your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.
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.
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.
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'
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.
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName.
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.
The same error occurred when I had another variable named mythread. That variable overwrote this and that's why I got error
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.
Ok, this one has me tearing my hair out:
I have a multi-process program, with separate workers each working on a given task.
When a KeyboardInterrupt comes, I want each worker to save its internal state to a file, so it can continue where it left off next time.
HOWEVER...
It looks like the dictionary which contains information about the state is vanishing before this can happen!
How? The exit() function is accessing a more globally scoped version of the dictionary... and it turns out that the various run() (and subordinate to run()) functions have been creating their own version of the variable.
Nothing strange about that...
Except...
All of them have been using the self. keyword.
Which, if my understanding is correct, should mean they are always accessing the instance-wide version of the variable... not creating their own!
Here's a simplified version of the code:
import multiprocessing
import atexit
import signal
import sys
import json
class Worker(multiprocessing.Process):
def __init__(self, my_string_1, my_string_2):
# Inherit the __init_ from Process, very important or we will get errors
super(Worker, self).__init__()
# Make sure we know what to do when called to exit
atexit.register(self.exit)
signal.signal(signal.SIGTERM, self.exit)
self.my_dictionary = {
'my_string_1' : my_string_1,
'my_string_2' : my_string_2
}
def run(self):
self.my_dictionary = {
'new_string' : 'Watch me make weird stuff happen!'
}
try:
while True:
print(self.my_dictionary['my_string_1'] + " " + self.my_dictionary['my_string_2'])
except (KeyboardInterrupt, SystemExit):
self.exit()
def exit(self):
# Write the relevant data to file
info_for_file = {
'my_dictionary': self.my_dictionary
}
print(info_for_file) # For easier debugging
save_file = open('save.log', 'w')
json.dump(info_for_file, save_file)
save_file.close()
# Exit
sys.exit()
if __name__ == '__main__':
strings_list = ["Hello", "World", "Ehlo", "Wrld"]
instances = []
try:
for i in range(len(strings_list) - 2):
my_string_1 = strings_list[i]
my_string_2 = strings_list[i + 1]
instance = Worker(my_string_1, my_string_2)
instances.append(instance)
instance.start()
for instance in instances:
instance.join()
except (KeyboardInterrupt, SystemExit):
for instance in instances:
instance.exit()
instance.close()
On run we get the following traceback...
Process Worker-2:
Process Worker-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/multiprocessing/process.py", line 249, in _bootstrap
self.run()
Traceback (most recent call last):
File "/usr/lib/python3.5/multiprocessing/process.py", line 249, in _bootstrap
self.run()
File "<stdin>", line 18, in run
File "<stdin>", line 18, in run
KeyError: 'my_string_1'
KeyError: 'my_string_1'
In other words, even though the key my_string_1 was explicitly added during init, the run() function is accessing a new version of self.my_dictionary which does not contain that key!
Again, this would be expected if we were dealing with a normal variable (my_dictionary instead of self.my_dictionary) but I thought that self.variables were always instance-wide...
What is going on here?
Your problem can basically be represented by the following:
class Test:
def __init__(self):
self.x = 1
def run(self):
self.x = 2
if self.x != 1:
print("self.x isn't 1!")
t = Test()
t.run()
Note what run is doing.
You overwrite your instance member self.my_dictionary with incompatible data when you write
self.my_dictionary = {
'new_string' : 'Watch me make weird stuff happen!'
}
Then try to use that incompatible data when you say
print(self.my_dictionary['my_string_1']...
It's not clear precisely what your intent is when you overwrite my_dictionary, but that's why you're getting the error. You'll need to rethink your logic.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
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
Your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.
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.
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.
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'
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.
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName.
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.
The same error occurred when I had another variable named mythread. That variable overwrote this and that's why I got error
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.
I am confused about how inherited class attributes are initialized. I get an AttributeError on a child attribute that I thought was well defined.
I noticed that swapping the order of the super call to the parent after the definition does not yield an error but I do not understand why.
I have not been able to reproduce that error without using processes (I can post that test code too but I think this is lengthy enough), it seems then that the order in which the super is called does not matter.
Edit : It is probably because of running a process before counter is even defined that yiels the exception, but the problem does not happen if I use Thread instead of Process.
I might be missing something about how initializers work or doing something wrong.
Why do I get an Attribute error?
Why swapping the two line solves (or masks) the problem?
Why does this problem does not happen using threads instead of processes?
I am using the code below.
Thanks for your help.
Here is the code that reproduces the issue. I tried my best to make it stand-alone.
from multiprocessing import Process
from multiprocessing import Queue
class Parent(object):
def __init__(self):
self._stuff_queue = Queue()
self._process = Process(target=self._do_something)
self._process.start()
def _do_something(self):
while True:
stuff = self._stuff_queue.get()
if stuff is not None:
self.something(stuff)
else:
break
def feed(self, stuff):
self._stuff_queue.put(stuff)
def something(self):
raise NotImplementedError("Implement this something !")
class Child(Parent):
def __init__(self):
# --- Swapping those two lines avoids getting the AttributeError --- #
super(Child, self).__init__() # Same thing using Parent.__init__(self)
self.counter = 0
def something(self, stuff):
self.counter += 1
print "Got stuff"
c = Child()
c.feed("Hi SO!")
c.feed(None) # Just to stop
Here is the message I get :
File "/home/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "test_process.py", line 14, in _do_something
self.something(stuff)
File "test_process.py", line 30, in something
self.counter += 1
AttributeError: 'Child' object has no attribute 'counter'