setitem和getitem - python

时间:2013-12-03 16:24:20

标签: python class

我创建了一个创建矢量的python程序。现在我想使用函数__setitem____getitem__设置项目。例如,如果vector = Vec()vector[3] = 26将空向量更改为[0, 0, 0, 26]。我需要覆盖__getitem____setitem__我列出了下面的代码,但是我遇到了get和set函数的麻烦。有什么建议吗?

class Vec:
    def __init__(self, length = 0):
        self.vector = [0]*length

    def __str__(self):
        return '[{}]'.format(', '.join(str(i) for i in self.vector))
        #This formats the output according to the homework.
        #Adds '[' and ']' and commas between each 0

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

    def extend(self, newLen):
        self.vector.append([0]*newLen)
        return (', '.join(str(j) for j in self.vector))

    def __setitem__(self, key, item):
        self.vector[key] = item

    def __getitem__(self, key):
        return self.vector[key]

4 个答案:

答案 0 :(得分:9)

你有几个问题:

  1. extend基本上将一个新的向量附加到原始的末尾,而不是增加原始的长度。目前尚不清楚它是否需要返回修改后的矢量的字符串表示(除非它仅用于调试目的)。

    def extend(self, newlength):
        # Assume newlength is greater than the old
        self.vector.extend([0] * (newlength - len(self)))
    
  2. 如果密钥太大,
  3. __setitem__需要致电extend

    def __setitem__(self, key, item):
        if key >= len(self):
            self.vector.extend(key+1)
        self.vector[key] = item
    
  4. __getitem__需要访问基础列表,而不是使用未定义的属性

    def __getitem__(self, key):
        # It's probably better to catch any IndexError to at least provide
        # a class-specific exception
        return self.vector[key]
    

答案 1 :(得分:6)

问题是由于length方法定义中给定__init__()关键字参数的默认值,您创建的向量没有长度。试试这个:

vector = Vec(4)
vector[3] = 26
print vector  # --> [0, 0, 0, 26]

答案 2 :(得分:1)

您需要调整__getitem____setitem__以委托给基础列表:

def __setitem__(self, key, item):
    self.vector[key] = item 
    # return doesn't make sense here

def __getitem__(self, key):
    # not sure what self.__key is ? Let's return value from index in `self.vector` instead
    return self.vector[key]

答案 3 :(得分:0)

如果这样做,在__str__中会更容易

return str(self.vector)