2016-01-27 49 views
1

當我試圖加載JSON文件時,返回我的函數時出現問題。這是要看的代碼。加載JSON時Python出錯返回

#!/usr/bin/python 
import os 
import json 

class Math(object): 
    def __init__(self):  
     self.__mathjsonfile__ = os.path.join(os.getcwd(),os.path.dirname(__file__),'server','json_data','math.json') 

    def load_mathfile(self): 
     with open(self.__mathjsonfile__) as i: 
      data = i.read() 
      math_data = json.loads(data) 
     self.math_data = math_data 

    def read_mathdata(self): 
     for numbers in self.math_data['numbers']: 
      print numbers['zero'] 
     for symbols in self.math_data['symbols']: 
      print symbols['percent'] 

start = Math() 
start.read_mathdata() 

我已經()結束了最後一個功能,因爲我似乎無法結束​​與return,仍然打印JSON的信息。

+0

爲什麼你使用面向對象的程序代碼是什麼? –

+0

你總是用'()'結束函數來運行它 - 查看代碼中的其他函數'read()','getcwd()'。 'return'用於從功能發回數據並停止運行功能。 – furas

回答

3

您可以用簡單的方式從一個函數返回的數據,就像下面:

class Math(object): 
    def __init__(self):  
     self.__mathjsonfile__ = os.path.join(os.getcwd(),os.path.dirname(__file__),'server','json_data','math.json') 

    def load_mathfile(self): 
     with open(self.__mathjsonfile__) as i: 
      data = i.read() 
      math_data = json.loads(data) 
     self.math_data = math_data 

    def read_mathdata(self): 
     data = [] 
     for numbers in self.math_data['numbers']: 
      data.append(numbers['zero']) 
     for symbols in self.math_data['symbols']: 
      data.append(numbers['percent']) 
     return data 

start = Math() 
my_data = start.read_mathdata() 
print my_data 

如果您想通過using the property decorator,使​​一個屬性,您可以:

@property 
    def read_mathdata(self): 
     pass 

然後你就可以這樣稱呼它:

my_data = start.read_mathdata 

爲什麼你想要做任何這是超出我的。