[英]Inherit from Python's and override __str__
I am interested in doing something similar to what Django is doing to lists, eg: 我对做类似Django对列表的操作感兴趣,例如:
In [4]: from TimePortal.models import Rules
In [5]: Rules.objects.all()
Out[5]: [<Rules: day_limit>]
I tried doing the following: 我尝试执行以下操作:
class TimeEntryList(list):
def __str__(self):
return ';'.join([str(i) for
i in self.__getslice__(0, self.__len__())])
Which seems to work in a normal Python shell: 这似乎可以在普通的Python shell中工作:
In [54]: a=TimeEntryList(('1-2','2-3'))
In [58]: print a
1-2;2-3
In [59]: str(a)
Out[59]: '1-2;2-3'
However in my application a TimeEntryList
instance is really a list of TimeEntry
objects defined like this: 但是在我的应用程序中, TimeEntryList
实例实际上是这样定义的TimeEntry
对象的列表:
class TimeEntry(object):
def __init__(self, start, end):
self.start = start
self.end = end
#self.duration = (self.end - self.start).seconds / 3600.0
@property
def duration(self):
return (self.end - self.start).seconds / 3600.0
@duration.setter
def duration(self, value):
self._duration = value
def __str__(self):
return '{} - {} '.format(dt.strftime(self.start, '%H:%M'),
dt.strftime(self.end, '%H:%M'),)
When I am printing a single entry everything is ok: 当我打印单个条目时,一切正常:
>>> print checker.entries[0]
08:30 - 11:00
When I try slicing, results are different: 当我尝试切片时,结果是不同的:
>>>print self.entries[0:2]
[<TimePortal.semantikCheckers.TimeEntry object at 0x93c7a6c>, <TimePortal.semantikCheckers.TimeEntry object at 0x93d2a4c>]
How do I inherit from list, and define __str__
so that print only slices works the following is output when issuing print self.entries[0:2]
: 我如何从列表继承,并定义__str__
以便仅打印切片在发出print self.entries[0:2]
时输出以下内容:
['08:30 - 11:00 ', '11:00 - 12:30 ']
I know this gives the desired out: 我知道这给出了期望的结果:
[str(i) for i in self.entries[:2]]
However my purpose here is learning a new technique and not necessarily working with what I already know. 但是,我在这里的目的是学习一种新技术,并不一定要与我已经知道的知识一起工作。
You need to override __repr__
of TimeEntry
(instead of changing the list implementation). 您需要重写TimeEntry
__repr__
(而不是更改列表实现)。 You can find an explanation about the difference between __repr__
and __str__
here: 您可以在此处找到有关__repr__
和__str__
的区别的解释:
Difference between __str__ and __repr__ in Python __str__和__repr__在Python中的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.