-2

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'
martineau
  • 112,593
  • 23
  • 157
  • 280
pigman
  • 33
  • 7

1 Answers1

1

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

esqew
  • 39,199
  • 27
  • 87
  • 126