用 return 结束函数时加载 JSON 时出现 Python 错误

标签 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 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_mathdata 成为一个属性,您可以通过using the property decorator :

    @property
    def read_mathdata(self):
        pass

然后你可以像这样调用它:

my_data = start.read_mathdata

我不明白你为什么要这么做。

关于用 return 结束函数时加载 JSON 时出现 Python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35027537/

相关文章:

python - 从 pandas 时间戳中提取日期和时间

javascript - JS 数组循环次数为 1 Off

java - 返回语句可以像 printf 一样格式化吗?

返回未定义的javascript函数

c# - 有趣的代码片段

python - 如何在 Mac 上安装 Python 的 dlib?

python - 为什么 Helm 机要按方向键3次才能移动?

python - 同一页面上具有相同 radio 字段的多个 WTForm

android - 验证登录屏幕的 GET JSON 响应并转到主屏幕

json - 如何在不嵌入的情况下将 JSON 解码添加到外部库类型