Python Forum

Full Version: [Python Class] save method output to global file/list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

--------------
class Xyz(object):

Hi All,

I want to save mutliple method output to a global file so that I can use it in another method. I am able to the output when I run sigle method. However output is over writing when I run mutliple methods at same time. My code looks like this,

class Abc(object):

    def __init__(self, net, cost):
        self.net = net
        self.cost = cost
        self.output_file = None

    def method1(self):
        self.output_file = list()
		input = {'Class': 1, 'Range': 'top'}
		output_file.append(input)

    def method2(self):
        #self.output_file = list()
		input = {'Class': 2, 'Range': 'low'}
		output_file.append(input)

    def method3(self):
		for line in self.output_file:
			print line
	


I want to save method1 & 2 output to output_file and use it in mothod3. Could you please suggest how I can achieve this? Thanks in advance.
Something like this?

class FileMethod:

    _file = None

    def __init__(self):
        pass

    def __enter__(self):
        try:
            self._file = open("./logging", "w")
            return self
        except IOError as e:
            print(e)

    def method1(self):
        self._file.writelines("Printing from method1")
        self._file.writelines('\n')

    def method2(self):
        self._file.writelines("Printing from method2")
        self._file.writelines('\n')

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._file.close()


def main():
    with FileMethod() as file:
        file.method1()
        file.method2()


if __name__ == "__main__":
    main()
Output:
cat logging Printing from method1 Printing from method2
self.output_file = None
to
self.output_file = []
Thanks a lot Shivraj and Windspar, for your time.
I have tested Windspar suggestion and its working perfectly as required. Dance