1

I'm having an issue returning my function when trying to load a JSON file. Here is the code to look at.

#!/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()

I've ended the last function with () because I can't seem to end read_mathdata with return and still print the JSON information.

ozy
  • 57
  • 1
  • 11
  • Why are you using OOP for what is clearly procedural code? –  Jan 27 '16 at 02:03
  • you have always ends function with `()` to run it - see other functions in your code `read()`, `getcwd()`. `return` is use to send data back from function and to stop running function. – furas Jan 27 '16 at 02:07

1 Answers1

3

You can return data from a function using the straightforward way, like that below:

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

If you want to make read_mathdata a property you can by using the property decorator:

    @property
    def read_mathdata(self):
        pass

Then you can call it like so:

my_data = start.read_mathdata

Why you'd want to do any of this is beyond me.

Community
  • 1
  • 1