class - Python getslice Item Operator Override Function not working -


practicing examples posted here learning python oop. looking output of '1 4', instead throws error below.

class fakelist:      def __getslice___(self,start,end):          return str(start) + " " + str(end)  f = fakelist()  f[1:4] 

note: using f.__getitem__(1, 4) results in correct output--"1 4", shown in link above.

traceback (most recent call last) in () ----> 1 f[1:4]

typeerror: 'fakelist' object not subscriptable

as mentioned in comments, __getitem__ method takes 1 parameter of slice type, , can access start/end of range via slice.start , slice.stop, here example more debug output show going on:

class fakelist:      def __getitem__(self, slice_):          print('slice_', slice_)          print('type(slice_)', type(slice_))          print('dir(slice_)', dir(slice_))          return str(slice_.start) + " " + str(slice_.stop)  f = fakelist()  print(f[1:4]) 

the output:

slice_ slice(1, 4, none)  type(slice_) <class 'slice'>  dir(slice_) ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'indices', 'start', 'step', 'stop']  1 4 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -