oz123
oz123

Reputation: 28858

Inherit from Python's and override __str__

I am interested in doing something similar to what Django is doing to lists, e.g:

In django shell

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:

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:

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>]

my question is:

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]:

['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.

Upvotes: 0

Views: 2686

Answers (1)

Rapolas K.
Rapolas K.

Reputation: 1709

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

Upvotes: 5

Related Questions