0

我有兴趣做一些类似于 Django 对列表所做的事情,例如:

在 Django 外壳中

In [4]: from TimePortal.models import Rules

In [5]: Rules.objects.all()
Out[5]: [<Rules: day_limit>]

我尝试执行以下操作:

class TimeEntryList(list):

    def __str__(self):
        return ';'.join([str(i) for
                        i in self.__getslice__(0, self.__len__())])

这似乎在普通的 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'

然而,在我的应用程序中,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'),)

当我打印单个条目时,一切正常:

>>> print checker.entries[0]
08:30 - 11:00 

当我尝试切片时,结果不同:

>>>print self.entries[0:2]
[<TimePortal.semantikCheckers.TimeEntry object at 0x93c7a6c>, <TimePortal.semantikCheckers.TimeEntry object at 0x93d2a4c>]

我的问题是:

我如何从列表中继承,并定义__str__以便仅打印切片工作,发出时输出以下内容print self.entries[0:2]

['08:30 - 11:00 ', '11:00 - 12:30 ']

我知道这给出了期望的结果:

[str(i) for i in self.entries[:2]]

然而,我在这里的目的是学习一种新技术,而不一定要使用我已经知道的东西。

4

1 回答 1

5

You need to override __repr__ of TimeEntry (instead of changing the list implementation). You can find an explanation about the difference between __repr__ and __str__ here:

Difference between __str__ and __repr__ in Python

于 2013-08-28T10:38:45.160 回答