问题描述
我正在尝试将 JSON 文件中的一些数据存储到一个类变量中,该类变量可以被该类之外的任何其他函数访问。 JSON 文件中的数据总是不同的,所以我使用了一个线程。
这是我的代码示例。
class fruitStand(threading.Thread):
fruitAmount = []
def __init__(self):
threading.Thread.__init__(self)
def run(self):
with open("fruitDatafile.json","r") as fruitDatafile:
fruitData = json.load(fruitDatafile)
fruitValue = [
fruitData["apples"],fruitData["pears"],fruitData["watermelons"],fruitData["lemons"]]
while True:
self.fruitAmount.clear()
for item in fruitValue:
self.fruitAmount.append(item)
time.sleep(3100)
fStand = fruitStand()
fStand.start()
print(fStand.fruitAmount)
数据似乎正确存储到 fruitAmount
变量中,但是当我尝试从类外部访问它时,它显示好像里面没有任何内容。
解决方法
print(fStand.fruitAmount) 正在线程完成之前运行,因此它是空的。尝试在 run 方法中打印它或等待线程完成使用 fStand.join() 方法