将数据从 JSON 文件转储到类变量并从类外部访问数据

问题描述

我正在尝试将 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() 方法

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...