J
Jane Austine
Please see the following code:
--------------------------------
class rev_wrap(object):
def __init__(self,l):
self.l=l
def __getitem__(self,i):
return self.l[-i-1]
class rev_subclass(list):
def __getitem__(self,i):
return list.__getitem__(self,-i-1)
if __name__=='__main__':
l=rev_wrap([1,2,3])
assert l[0]==3
assert list(l)==[3,2,1]
l=rev_subclass([1,2,3])
assert l[0]==3
assert list(l)==[3,2,1]
I know there is "reversed" and "reverse" but that's not the point. The
code fails at the last line.
Now that UserList is deprecated(not recommended) I suppose subclassing
built-in types are preferable than wrapping them. How do I properly
change the behaviours of built-in types? I think I have to override
__iter__ and next to pass the last line. Is it a good style? If so,
what is the most recommended way of implementing them?
Thank you in advance.
Jane
--------------------------------
class rev_wrap(object):
def __init__(self,l):
self.l=l
def __getitem__(self,i):
return self.l[-i-1]
class rev_subclass(list):
def __getitem__(self,i):
return list.__getitem__(self,-i-1)
if __name__=='__main__':
l=rev_wrap([1,2,3])
assert l[0]==3
assert list(l)==[3,2,1]
l=rev_subclass([1,2,3])
assert l[0]==3
assert list(l)==[3,2,1]
I know there is "reversed" and "reverse" but that's not the point. The
code fails at the last line.
Now that UserList is deprecated(not recommended) I suppose subclassing
built-in types are preferable than wrapping them. How do I properly
change the behaviours of built-in types? I think I have to override
__iter__ and next to pass the last line. Is it a good style? If so,
what is the most recommended way of implementing them?
Thank you in advance.
Jane