Append/Write 具有实例的值
Append/Write with values of an instance
所以我是在 python 中使用 classes 的新手,但是我的这个项目 Euler(q 81) 是使用 classes 完成的,只是有点更棘手?我猜?
我可以获取 (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>
^^ 我希望这最后一行给我值,而不是实例,但是如何?
我的矩阵 class 看起来像这样:
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" 是 class 名称,"matrix" 是文件名和我的 class minSum 的参数,以便能够访问该文件。
如果您需要查看更多矩阵文件,请告诉我。
谢谢。
当您尝试将实例写入文本文件时似乎遇到了另一个错误,但这里有一种打印值而不是实例的方法:
__repr__
方法可让您定义对象在打印时的外观。
向 Supplies
class 添加一个 __repr__
方法,如下所示:
class Supplies:
def __init__(self, supp):
if isinstance(supp, list):
self.value = supp[0]
def __repr__(self):
return str(self.value)
每当您打印 Supplies
实例时,Python 将打印它的 value
属性。请注意 value
不能保证在 Supplies
class 中定义,因此您可能想要初始化它或在尝试将其转换为 [=13= 中的字符串之前进行检查]方法。
编辑
如果您希望 newList
包含每个 Supplies
实例的值,您可以只附加值而不是实例:
newList.append(y.value)
而不是:
newList.append(y)
所以我是在 python 中使用 classes 的新手,但是我的这个项目 Euler(q 81) 是使用 classes 完成的,只是有点更棘手?我猜?
我可以获取 (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>
^^ 我希望这最后一行给我值,而不是实例,但是如何?
我的矩阵 class 看起来像这样:
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" 是 class 名称,"matrix" 是文件名和我的 class minSum 的参数,以便能够访问该文件。
如果您需要查看更多矩阵文件,请告诉我。
谢谢。
当您尝试将实例写入文本文件时似乎遇到了另一个错误,但这里有一种打印值而不是实例的方法:
__repr__
方法可让您定义对象在打印时的外观。
向 Supplies
class 添加一个 __repr__
方法,如下所示:
class Supplies:
def __init__(self, supp):
if isinstance(supp, list):
self.value = supp[0]
def __repr__(self):
return str(self.value)
每当您打印 Supplies
实例时,Python 将打印它的 value
属性。请注意 value
不能保证在 Supplies
class 中定义,因此您可能想要初始化它或在尝试将其转换为 [=13= 中的字符串之前进行检查]方法。
编辑
如果您希望 newList
包含每个 Supplies
实例的值,您可以只附加值而不是实例:
newList.append(y.value)
而不是:
newList.append(y)