相关疑难解决方法(0)

setitem和getitem - python

我创建了一个创建矢量的python程序.现在,我想设置使用功能的项目__setitem____getitem__.因此,例如,if 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 …
Run Code Online (Sandbox Code Playgroud)

python class

19
推荐指数
3
解决办法
6万
查看次数

标签 统计

class ×1

python ×1