![]() |
[Python Class] save method output to global file/list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: [Python Class] save method output to global file/list (/thread-7132.html) |
[Python Class] save method output to global file/list - Vijay - Dec-22-2017 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. RE: [Python Class] save method output to global file/list - hshivaraj - Dec-22-2017 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()
RE: [Python Class] save method output to global file/list - Windspar - Dec-22-2017 self.output_file = Noneto self.output_file = [] RE: [Python Class] save method output to global file/list - Vijay - Dec-23-2017 Thanks a lot Shivraj and Windspar, for your time. I have tested Windspar suggestion and its working perfectly as required. ![]() |