Oz1*_*123 0 python inheritance overriding
我有兴趣做类似于Django对列表所做的事情,例如:
In [4]: from TimePortal.models import Rules
In [5]: Rules.objects.all()
Out[5]: [<Rules: day_limit>]
Run Code Online (Sandbox Code Playgroud)
我尝试过以下操作:
class TimeEntryList(list):
def __str__(self):
return ';'.join([str(i) for
i in self.__getslice__(0, self.__len__())])
Run Code Online (Sandbox Code Playgroud)
这似乎适用于普通的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'
Run Code Online (Sandbox Code Playgroud)
但是在我的应用程序中,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'),)
Run Code Online (Sandbox Code Playgroud)
当我打印单个条目时,一切正常:
>>> print checker.entries[0]
08:30 - 11:00
Run Code Online (Sandbox Code Playgroud)
当我尝试切片时,结果是不同的:
>>>print self.entries[0:2]
[<TimePortal.semantikCheckers.TimeEntry object at 0x93c7a6c>, <TimePortal.semantikCheckers.TimeEntry object at 0x93d2a4c>]
Run Code Online (Sandbox Code Playgroud)
如何从列表继承,并定义__str__以便只打印切片工作时,在发出时输出以下内容print self.entries[0:2]:
['08:30 - 11:00 ', '11:00 - 12:30 ']
Run Code Online (Sandbox Code Playgroud)
我知道这给了你想要的东西:
[str(i) for i in self.entries[:2]]
Run Code Online (Sandbox Code Playgroud)
然而,我的目的是学习一种新技术,而不一定与我已经知道的一起工作.
你需要重写__repr__的TimeEntry(而不是改变列表实现).你可以找到关于__repr__和__str__这里之间的区别的解释: