setitem 和 getitem -- python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20356401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setitem and getitem -- python
提问by user3014014
I've created a python program that makes a vector. Now i want to set an item using a function__setitem__and__getitem__. So for example, ifvector = Vec()andvector[3] = 26would change an empty vector to[0, 0, 0, 26]. I need to override the__getitem__and__setitem__I've listed the code below, but i'm having troubles with the get and set functions. Any advice?
我创建了一个生成向量的 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]
回答by Jon Clements
You need to adapt your __getitem__and __setitem__to delegate to the underlying list:
您需要调整您的__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]
回答by chepner
You have several problems:
你有几个问题:
extendis appending essentially a new vector to the end of the original, rather than increasing the length of the original. It's not clear that it needs to return a string representation of the modified vector (unless it's just for debugging purposes).def extend(self, newlength): # Assume newlength is greater than the old self.vector.extend([0] * (newlength - len(self)))__setitem__needs to callextendif the key is too large.def __setitem__(self, key, item): if key >= len(self): self.vector.extend(key+1) self.vector[key] = item__getitem__needs to access the underlying list, not use an undefined attributedef __getitem__(self, key): # It's probably better to catch any IndexError to at least provide # a class-specific exception return self.vector[key]
extend本质上是在原始向量的末尾附加一个新向量,而不是增加原始向量的长度。不清楚它是否需要返回修改后的向量的字符串表示(除非它只是为了调试目的)。def extend(self, newlength): # Assume newlength is greater than the old self.vector.extend([0] * (newlength - len(self)))__setitem__extend如果键太大,需要调用。def __setitem__(self, key, item): if key >= len(self): self.vector.extend(key+1) self.vector[key] = item__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]
回答by martineau
The problem is the vector you created has no length because of the default value given the lengthkeyword argument in the __init__()method definition. Try this:
问题是您创建的向量没有长度,因为length在__init__()方法定义中给定了关键字参数的默认值。尝试这个:
vector = Vec(4)
vector[3] = 26
print vector # --> [0, 0, 0, 26]
回答by Superior
It would be easier in __str__if you do this
__str__如果你这样做会更容易
return str(self.vector)

