I am trying to define a default style list object:
class ilist(list):
def __init__(self,r=list(),dft=None):
list.__init__(self,r)
self.dft=dft
def __getitem__(self,n):
if len(self)<=n:
for i in range(n-len(self)+1):
self.append(self.dft)
for i,v in enumerate(self):
if i+1==len(self):
return v
x=ilist()
print x[4]
print x
It works.
>>>
None
[None, None, None, None, None]
But I think it's terrible to query my ilist. I've tried the following method:
def __getitem__(self,n):
from operator import getitem
if len(self)<=n:
for i in range(n-len(self)+1):
self.append(self.dft)
return getitem(self,n)
but the fact shows it totally equals self[n] and causes RuntimeError: maximum recursion depth exceeded
I also tried to borrow the parent class list
method .But the form isx.__getitem__(y)
. I don't know how to adapt it to ilist.
So finally my terrible solution comes out. Raw and brute force..Is there any effecient or simple solution? Thanks in advance.