Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

python - Dump data from JSON file to a class variable and access data from outside the class

I'm trying to store some data from a JSON file into a class variable that can be accessed by any other functions outside the class. The data in the JSON file will always be different, so I'm using a thread.

This is an example of my code.

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)

The data seems to be stored correctly into the fruitAmount variable, but when I try to access it from outside the class, it shows as if there's nothing in it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

print(fStand.fruitAmount) is being run before the thread is finished so it is empty. try printing it inside the run method or wait till the thread is complete using fStand.join() method


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...