简体   繁体   English

如何在课堂上实现str函数?

[英]How can I implement the str function in my class?

I have created this class that returns non zero values of a vector. 我创建了此类,该类返回向量的非零值。

class SparVec:

    def __init__(self,length):
        self.val={}
        self.len=length

    def __len__(self):
        return self.len

    def __getitem__(self, index):
        return self.val.get(index,0)
    def __setitem__(self,index,value):
        if value !=0:
             self.val[index]=value
        self.len=max(index,self.len)
    # Adding vectors
    def __add__(self, other):
        # Add Two vectors
        length=self.len
        result=SparVec(length)
        for index in self.val:
            result[index]=self[index]+other[index]
        for index in other.val:
            if index not in self.val:
                result[index]=other[index]
        return result

    def nonzeros(self):
        return 'Sparse Vector {}'.format(self.val)

if __name__ == '__main__':

    a = SparVec(4)
    a[2] = 9.2
    a[0] = -1
    a[3] = 0
    print a
    print a.nonzeros()

    b = SparVec(5)
    b[1] = 1
    print b
    print b.nonzeros()

    c = a+b
    print c
    print c.nonzeros()

So far so good. 到现在为止还挺好。 I get the values I want with the nonzeros function. 我可以通过nonzeros函数获得所需的值。 The problem is how to have the following output when I print a or b. 问题是当我打印a或b时如何具有以下输出。 Tip: Without creating a new list that stores all the items as zeros and then print it. 提示:无需创建将所有项目存储为零的新列表,然后打印它。

print a
[0]=-1 [1]=0 [2]=9.2 [3]=0

You can use str.join with a generator expression that iterates over the length of the sparse vector and outputs the key-value pairs with a default value of 0: 您可以将str.join与生成器表达式一起使用,该表达式在稀疏向量的长度上进行迭代,并输出默认值为0的键/值对:

def __str__(self):
    return ' '.join('[{}]={}'.format(i, self.val.get(i, 0)) for i in range(self.len))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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