如何在python中使对象变为可变?

时间:2015-12-26 04:49:06

标签: python class

因此,根据我所收集的内容,默认情况下,用户自定义的类应该是可变的,但我经历了相反的情况。这是我的代码:

import copy
class vector:

    def __init__(self, entries):
        if type(entries) == list:
            self.elements = []
            self.dimensionality = len(entries)
            for entry in entries:
                self.elements.append(entry)
        elif type(entries) == vector:
            self.elements = entries.elements

    def __getitem__(self,index):
        return self.elements[index]

    def __add__(self, otherVector):
        if len(self) != len(otherVector):
            raise RuntimeError("Cannot add these vectors")
        sumt = []
        for entry in len(self):
            sumt.append(self.elements[entry] + otherVector.elements[entry])
        return vector(sumt)

    def __len__(self):
        return len(self.elements)

    def __eq__(self, otherVariable):
        return size(self) == size(otherVariable)

    def size(x):
        return (x * x)**(1/2)

    def taxi(x):
        taxiSize = 0
        for entry in x.elements:
            taxiSize += entry
        return taxiSize

class matrix:
    def __init__(self, entries):
        for i in entries:
            if len(entries[0]) != len(i):
                raise RuntimeError("All rows of matrix must contain the same number of entries")
        self.elements = []
        for row in entries:
            self.elements.append(vector(row))

    def __add__(self, otherMatrix):
        if len(self.elements) != len(otherMatrix.elements):
            raise RuntimeError("Cannot add matrices of different sizes")
        if len(self.elements[0]) != len(otherMatrix.elements[0]):
            raise RuntimeError("Cannot add matrices of different sizes")

        sumt = []
        row = []
        for entry in self.elements[0]:
            row.append(0)
        for i in self.elements:
            sumt.append(row)
        sumf = matrix(sumt)
        for i in range(len(self.elements)):
            for j in range(len(self.elements[0])):
                sumf.elements[i][j] = self.elements[i][j] + otherMatrix.elements[i][j]    #error is on this line
        return sumf

matrix([[3,4],[1,2]]) + matrix([[3,4],[1,2]])

错误:

Traceback (most recent call last):
  File "/Users/sebpole/Documents/vectors.py", line 164, in <module>
    matrix([[3,4],[1,2]]) + matrix([[3,4],[1,2]])
  File "/Users/sebpole/Documents/vectors.py", line 143, in __add__
    sumf.elements[i][j] = self.elements[i][j] + otherMatrix.elements[i][j]
TypeError: 'vector' object does not support item assignment

似乎Python并不喜欢我改变我的矢量类的条目,这让我感到困惑,因为我认为这个类应该是不可变的。
为什么我的对象是不可变的,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

项目分配是通过您的班级未定义的__setitem__() method启用的。

答案 1 :(得分:0)

这不是一个可变性的问题。这是一个关于您的类是否支持索引赋值的问题。

要重新创建问题:

v0 = vector(..)
v1 = vector(..)
v0[0] = v1  # doesn't make sense with current implementation!

您的自定义矢量类不支持此操作,是导致失败的原因。

编辑:正如@Ignacio指出的那样,您需要定义__setitem__() method,但您还需要__get_item()__方法(以允许v0[0] + v1[0]工作)。