I'll frame this in the fact that I'm kind of a newbie to Python and I'm taking my first stab at writing a class. What I'd like to achieve is for the class to open a text file and return a value from the file based on user input. The text file contains information in a 2D array like this:
20,21,22
23,24,25
26,27,28
The value is retrieved from this text file and assigned to a new variable, so that the variable can be printed and also used later in a calculation. I've been able to do this without difficulty outside of a class, but getting this to work in a class has been frustrating. Here's the code I have so far in Python 2.7:
im_new = []
class Read(object):
def __init__(self, row, col, newvar):
self.row = row
self.col = col
self.newvar = newvar
display_list = []
self.newvar = []
with open("Array.txt", "r") as data_file:
for line in data_file:
display_list.append(line.strip().split(','))
def __str__(self):
self.newvar = (display_list[self.row][self.col])
return self.newvar
immem = Read( 1, 1, im_new)
print "OUTPUT: ", im_new
Ideally, I'd get "OUTPUT: 24", but instead I get "OUTPUT: []". I'm not sure what I'm doing wrong. Any help would be appreciated.
im_new, which is initialized as an emptylistand never modified.self.beforedisplay_list. (You've got it on all of your other attributes, so I assume you understand what it means, and this is effectively just a typo?)im_newinstead ofimmem. It's the latter that holds yourReadinstance, which has a__str__method, which does what you want.