简体   繁体   English

附加/写入实例值

[英]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? 因此,我是使用python类的新手,但是我使用类完成了这个Euler(q 81)项目,只是有点棘手? 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. 我可以获取(2n + 1 * 2n + 1)网格的值,但是我无法使用它们将值追加到另一个列表甚至写入文件。

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. “ Matrix”是类名,“ matrix”是文件名和提供给我的类minSum的自变量,以能够访问此文件。

If you need to see any more of the matrix file let me know. 如果您需要查看更多矩阵文件,请告诉我。

Thanks. 谢谢。

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. __repr__方法使您可以定义对象在打印时的外观。

Add a __repr__ method to the Supplies class like so: __repr__方法添加到Supplies类,如下所示:

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. 每当您打印Supplies实例时,Python都会打印其value属性。 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. 请注意,不能保证在Supplies类中定义该value因此您可能希望对其进行初始化或检查,然后再尝试将其转换为__repr__方法中的字符串。

Edit 编辑

If you want newList to contain the values of each Supplies instance you could just append the value instead of the instance: 如果希望newList包含每个Supplies实例的值,则可以仅附加该值而不是实例:

newList.append(y.value)

instead of: 代替:

newList.append(y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM