inheritance - Inherit from Python's and override __str__ -


i interested in doing similar django doing lists, e.g:

in django shell

in [4]: timeportal.models import rules  in [5]: rules.objects.all() out[5]: [<rules: day_limit>] 

i tried doing following:

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

which seems work in normal python shell:

in [54]: a=timeentrylist(('1-2','2-3')) in [58]: print 1-2;2-3  in [59]: str(a) out[59]: '1-2;2-3' 

however in application timeentrylist instance list of timeentry objects defined 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 printing single entry ok:

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

when try slicing, results different:

>>>print self.entries[0:2] [<timeportal.semantikcheckers.timeentry object @ 0x93c7a6c>, <timeportal.semantikcheckers.timeentry object @ 0x93d2a4c>] 

my question is:

how inherit list, , define __str__ print slices works following output when issuing print self.entries[0:2]:

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

i know gives desired out:

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

however purpose here learning new technique , not working know.

you need override __repr__ of timeentry (instead of changing list implementation). can find explanation difference between __repr__ , __str__ here:

difference between __str__ , __repr__ in python


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -