[英]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: 有没有一种方法可以在
A
上定义__str__
,这样我就可以通过这种方式传递索引:
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: 并获得
__str__
以利用索引并返回类似以下内容:
return "var_a is " + str(var_a[idx]) + ", var_b is" + str(var_b[idx])
To format strings with parameters, use __format__
: 要使用参数格式化字符串,请使用
__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__
. 您要查找的是
__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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.