I want to implement my own type of list called Stack
. I also want to add slicing functionality with the __getitem__
method like so:
JavaScript
x
10
10
1
class Stack():
2
def __init__(self):
3
self.items = []
4
5
def __getitem__(self, slc):
6
return self.items[slc]
7
8
def append(self, item):
9
self.items.append(item)
10
Now if I create a Stack
instance and append some elements to it I get the Stack
type:
JavaScript
1
6
1
st = Stack()
2
st.append('hi')
3
st.append('bye')
4
st.append('hello')
5
print(type(st)) # Stack type
6
but if I slice my Stack, it becomes a list again:
JavaScript
1
3
1
st_sliced = st[1:2]
2
print(type(st_sliced)) # List type
3
how can I make st_sliced to stay Stack
type after slicing?
Advertisement
Answer
return self.items[slc]
return a list – this is why the type is not a Stack anymore.
The code below keep the type as Stack.
JavaScript
1
21
21
1
class Stack:
2
def __init__(self, items=None):
3
if items is None:
4
items = []
5
self.items = items
6
7
def __getitem__(self, slc):
8
return Stack(self.items[slc])
9
10
def append(self, item):
11
self.items.append(item)
12
13
14
st = Stack()
15
st.append('hi')
16
st.append('bye')
17
st.append('hello')
18
print(type(st))
19
st_sliced = st[1:2]
20
print(type(st_sliced))
21