简体   繁体   中英

How do I make an object mutable in python?

So from what I've gathered user-made classes are supposed to be mutable by default, but I've experienced the opposite. Here's my code:

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]])

And the error:

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

seems like Python doesn't like my changing the entries of my vector class, which is confusing me because I thought the class was supposed to be immutable.
Why is my object immutable, and how can I fix this?

通过__setitem__()方法启用项目分配,您的类未定义该方法

This is not a question of mutability. This is a question of whether your class supports an indexed assignment.

To recreate the problem:

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

Your custom vector class doesn't support this operation, is the reason for the failure.

EDIT: As @Ignacio has pointed out, you need the __setitem__() method defined, but you also need the __get_item()__ method (to allow v0[0] + v1[0] to work ) defined as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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