Blue Eden
Blue Eden

Reputation: 59

Append/Write with values of an instance

So I'm new to working with classes in python, but this project Euler(q 81) I have is done using classes just to be a bit more tricky? I guess?

I can get the values of a (2n+1 * 2n+1) grid, but I can't work with them to append to another list or even write to a file.

def minSum(matrix):
    file = open("pleasedeargodwork.txt", "w")
    newList = []

    for x in maxtrix.grids:
        for y in x:
            newList.append(y)
            print y,
            file.write(y,)
     print newList

>>> 1 7 2 5 6 2 9 2 5
>>> TypeError: must be string or read-only character buffer, not instance
>>> <matrix.Supplies instance at 0x0240E9B8>

^^ I would like this last line to give me the values, rather than the instance, but how?

My matrix class looks something like this:

class Matrix:
    def __init__(self, grids):
       self.size = len(grids) / 2
       self.grids = [[Supplies(s) for s in row] for row in grids]

class Supplies:
    def __init__(self, supp):
        if isinstance(supp, list):
            self.value = supp[0]

"Matrix" is the class name, "matrix" is the filename and an argument given to my class minSum to be able to access this file.

If you need to see any more of the matrix file let me know.

Thanks.

Upvotes: 0

Views: 65

Answers (1)

EngineerCamp
EngineerCamp

Reputation: 671

Looks like you have another error when you try to write an instance to the text file but here's a way to print the values instead of the instance:

The __repr__ method lets you define what the object looks like when it is printed.

Add a __repr__ method to the Supplies class like so:

class Supplies:
    def __init__(self, supp):
        if isinstance(supp, list):
            self.value = supp[0]

    def __repr__(self):
        return str(self.value)

Whenever you print a Supplies instance, Python will print its value attribute instead. Note that value is not guaranteed to be defined in the Supplies class so you might want to either initialize it or check before you attempt to convert it to a string in the __repr__ method.

Edit

If you want newList to contain the values of each Supplies instance you could just append the value instead of the instance:

newList.append(y.value)

instead of:

newList.append(y)

Upvotes: 1

Related Questions