Search 2D array in a class Python 2.7

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 one of a group of text files based on user input. The text files contain information like this:

 20,21,22
 23,24,25
 26,27,28

The text file is read as a 2D array. A value is read from this array 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 the class, but getting this to work in a class has been frustrating. Here's the code I have so far for Python 2.7:

im_new = []

class Read(object):
    def __init__(self, agev, table, row, col, newvar):
        self.agevar = agev
        self.table = table
        self.row = row
        self.col = col
        self.newvar = newvar

        display_list = []


        with open(self.table + str(self.agevar) + ".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])

immem = Read(40, "im", 1, 2, im_new)


print "Immediate Memory: " % im_new

Ideally, referencing the example text file, the output would be "Immediate Memory: 25", but the output I get is "Immediate Memory:" and when I print the value im_new in the console, I get "[]". I'm sure it's something very obvious that I'm missing. Any help would be appreciated. Thanks in advance.

Answers


There's something wrong with your code, it doesn't also run. I tried to fix:

im_new = []

class Read(object):
    def __init__(self, agev, table, row, col, newvar):
        self.agevar = agev
        self.table = table
        self.row = row
        self.col = col
        self.newvar = newvar

        self.display_list = []


        with open(self.table + str(self.agevar) + ".txt", "r") as data_file:
            for line in data_file:
                self.display_list.append(line.strip().split(','))

    def __str__(self):
        self.newvar = (self.display_list[self.row][self.col])
        return self.newvar

immem = Read(40, "im", 1, 2, im_new)


print "Immediate Memory: ", immem

This returns Immediate Memory: 25 like you're expecting, but I'm not sure it's what you want.


Need Your Help

Hide a div when another div is shown

javascript jquery html

I have 4 divs, two of them are shown on click (link), and hidden the same way. When I click the link for the other 2 divs, the first 2 should be hidden again and the other way around. Right now all 4

How do you rate multiple attributes of the same object?

ruby-on-rails ruby rating

I've not seen this feature as a plug in and was wondering how to achieve it, hopefully using rails.