简体   繁体   中英

Handle [] in __str__ method

I have a class that looks like this:

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

Is there a way I can define __str__ on A such that I can pass an index in this fashion:

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

and get __str__ to utilise the index and return something like:

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

To format strings with parameters, use __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])

Example:

>>> 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'

What you're looking for is __getitem__ , not __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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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