在__str__方法中处理[]

时间:2018-02-28 18:31:42

标签: python python-3.x

我有一个看起来像这样的课程:

class A(object):
    def __init__(self):  
         self.var_a = []
         self.var_b = []

有没有办法在__str__上定义A,这样我才能以这种方式传递索引:

instance_a = A()    
# do stuff with instance_a causing var_a and var_b to populate
print( instance_a[idx] )

并让__str__使用索引并返回类似的内容:

return "var_a is " + str(var_a[idx]) + ", var_b is" + str(var_b[idx]) 

2 个答案:

答案 0 :(得分:3)

要使用参数设置字符串格式,请使用__format__

class A(object):
    def __init__(self):  
         self.var_a = []
         self.var_b = []

    def __format__(self, idx):
        idx = int(idx)
        return "var_a is {}, var_b is {}".format(self.var_a[idx], self.var_b[idx])

示例:

>>> a = A()
>>> a.var_a=[4,5,6]
>>> a.var_b=[1,2,3]
>>> '{:1}'.format(a)
'var_a is 5, var_b is 2'

答案 1 :(得分:1)

您要找的是__getitem__,而不是__str__

class A(object):
    def __init__(self):
        self.var_a = []
        self.var_b = []

    def __getitem__(self, idx):
        return "var_a is " + str(self.var_a[idx]) + ", var_b is" + str(self.var_b[idx])


>>> a = A()
>>> a.var_a = [1,2,3]
>>> a.var_b = [4,5,6]
>>> print(a[2])
var_a is 3, var_b is6