用return结束函数时加载JSON时出现Python错误
在尝试加载JSON文件时,返回函数时遇到问题。下面是要查看的代码用return结束函数时加载JSON时出现Python错误,python,json,return,Python,Json,Return,在尝试加载JSON文件时,返回函数时遇到问题。下面是要查看的代码 #!/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 l
#!/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
结束read_mathdata
,然后仍然打印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):
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
如果要使read\u mathdata
成为属性,可以通过以下方式:
那么你可以这样称呼它:
my_data = start.read_mathdata
我无法理解您为什么要执行这些操作。为什么要使用OOP来编写程序代码?您总是以
()
结束函数来运行它-请参阅代码中的其他函数read()
,getcwd()
<代码>返回用于从函数发送数据并停止运行函数。
my_data = start.read_mathdata