簡體   English   中英

使用 class 重寫 function 以讀取 json 文件

[英]Rewriting a function to read json file using class

我正在編寫一個基於 json 文件的代碼,允許用戶在程序開頭選擇文件我寫了以下 function 來讀取文件,

file_name = input("Which .json file do you want to open? ")
def read_json_file(file_name):
    with open(file_name) as json_file:
        weather = js.load(json_file)
    return weather

后來,我被建議使用 class 重寫代碼以獲得更好的結構。 由於我對它不是很熟悉,所以我得到了幫助,這樣重寫了它

class Weather_data:
    def __init__(self):
        self.file_name = input("Which .json file do you want to open? ")

    def read_json_file(self):
        with open(self.file_name) as json_file:
            weather = js.load(json_file)
        return weather

但不是返回整個文件,有什么辦法只能返回 json 文件的特定部分? 例如

for i in range(len(weather['date'])):
   date = weather['value'][i]['date']
   value = weather['value'][i]['value']

即只有這兩個部分,但我希望能夠使用我定義的類訪問它們!

提前致謝!

基本上,將文件名輸入到 class 的init中,這樣當您創建一個實例時,它會請求 json 文件並將其設置為 class 實例的屬性。

看這里https://www.w3schools.com/python/python_classes.asp

例子:

class Weather_data:
    def __init__(self):
        self.file_name = input("Which .json file do you want to open? ")

    def read_json_file(self):
        with open(self.file_name) as json_file:
            weather = js.load(json_file)
        return weather

您還可以將天氣設置為 class 的屬性,即self.weather=js.load(json_file) ,然后使用您的 class 的實例訪問它。

編輯:

因為你編輯了你的問題。 您可以為每個要訪問的事物添加一個新屬性,然后通過 class 實例訪問它。

def read_json_file(self):
    with open(self.file_name) as json_file:
        self.weather = js.load(json_file)
    self.value=self.weather['value'] #or whatever you want

然后通過以下方式訪問:

weather_data=Weather_data() #instance of the class, will prompt for json file
weather_data.read_json_file() #runs the method
print(weather_data.value) #would print it
        

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM