setitem和getitem - python [英] setitem and getitem -- python

查看:157
本文介绍了setitem和getitem - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个python程序,使一个向量。现在我想使用函数 __ setitem __ __ getitem __ 设置项目。例如,如果 vector = Vec() vector [3] = 26 code> [0,0,0,26] 。我需要重写 __ getitem __ __ setitem __ 我列出了下面的代码,获取和设置函数。任何建议?

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?

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]


推荐答案

问题是向量您创建的没有长度,因为 __ init __()方法定义中的 length 关键字参数的默认值。尝试这样:

The problem is the vector you created has no length because of the default value given the length keyword argument in the __init__() method definition. Try this:

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

这篇关于setitem和getitem - python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆