我有一个类,我在其中存储slice
对象,因为实际的切片发生在应用程序的后续部分。但是,在这个函数的__repr__
中,我想要打印一些看起来像你自己写的东西。
class DelaySlice(object):
def __init__(self, obj, slice):
self.obj = obj
self.slice = slice
def __repr__(self):
return "%s[%s]" % (self.obj, self.slice)
class OtherObject(object):
def __repr__(self):
return "other_object_instance"
def __getitem__(self, slice):
return DelaySlice(self, slice)
有了这个,print(OtherObject()[:2]
打印other_object_instance[slice(None, 2, None)]
。我希望它能打印other_object_instance[:2]
。
我应该如何更改DelaySlice.__repr__
以实现我想要的目标?
答案 0 :(得分:0)
以下是针对明显情况执行此操作的代码段。
def __repr__(self):
sl_start = "" if self.slice.start is None else str(self.slice.start)
sl_stop = "" if self.slice.stop is None else str(self.slice.stop)
if self.slice.step is None:
sl_str = "%s:%s" % (sl_start, sl_stop)
else:
sl_str = "%s:%s:%s" % (sl_start, sl_stop, self.slice.step)
return "%s[%s]" % (self.obj, sl_str)
如果您将其用作DelaySlice.__repr__
,则会按预期打印
>>> OtherObject()[:2]
other_object_instance[:2]
>>> OtherObject()[1:2]
other_object_instance[1:2]
>>> OtherObject()[1:]
other_object_instance[1:]
>>> OtherObject()[1::4]
other_object_instance[1::4]