I tried to run two thread of class's function, and in function use instance variable. But when I show the adderss of that instance variable, why the address of self.flag of index = 3 is different with remain thread, and why exists two memory of instance variable in one object.
import time, threading, glob
class Test:
def __init__(self):
self.haha = 0
self.flag = True
def start(self, index):
print("start thread index:", index, "self.flag:", self.flag)
threading.Thread(target = self.create, args = (index, )).start()
def stop(self):
self.flag = False
for i in range(1):
time.sleep(1)
if self.flag == True:
print(True)
return True
print(False)
return False
def create(self, index):
print("before go while loop", index,"self.flag", self.flag, "id", id(self.flag)
, "id self:", id(self))
while self.flag:
print("in while loop", index,"self.flag", self.flag, "id", id(self.flag)
, "id self:", id(self))
time.sleep(3)
self.flag = True
a = Test()
a.start(2)
print("Start index: 2")
temp = threading.Thread(target = a.stop)
temp.start()
temp.join()
print("Pre Start index: 3")
a.start(3)
print("After Start index: 3")
print("Pre Start index: 4")
a.start(4)
print("After Start index: 4")
The result like:
start thread index: 2 self.flag: True
before go while loop 2 self.flag True id 7333536 id self: 139774008739392
Start index: 2
in while loop 2 self.flag True id 7333536 id self: 139774008739392
False
Pre Start index: 3
start thread index: 3 self.flag: False
before go while loop 3 self.flag False id 7333504 id self: 139774008739392
After Start index: 3
start thread index: 4 self.flag: True
before go while loop 4 self.flag True id 7333536 id self: 139774008739392
in while loop 4 self.flag True id 7333536 id self: 139774008739392
in while loop 2 self.flag True id 7333536 id self: 139774008739392
self.flag. In this case its the singletonsTrueorFalse, and not the address of the variable itself. Python variables don't have an address in that sense. They are key/value pairs in a namespace dictionary. In C for instance, the compiler would convert a variable name to an address in memory. But a python variable is more like a C++ std::map entry.