Skip to content

Commit 51c1799

Browse files
author
Vimal
committed
* Added 39-method-overloading-3.py
1 parent a999bcc commit 51c1799

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

39-method-overloading-3.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/env python
2+
3+
# 39-method-overloading-3.py
4+
5+
# We've seen that inherited methods can be overloaded.
6+
# This is possible using in-built functions as well.
7+
8+
# Let's see how we can overload methods from the `list` module.
9+
10+
11+
class MyList(list):
12+
13+
def __getitem__(self, index):
14+
if index == 0:
15+
raise IndexError
16+
if index > 0:
17+
index -= 1
18+
return list.__getitem__(self, index)
19+
20+
def __setitem__(self, index, value):
21+
if index == 0:
22+
raise IndexError
23+
if index > 0:
24+
index -= 1
25+
list.__setitem__(self, index, value)
26+
27+
x = MyList(['a', 'b', 'c'])
28+
print(x)
29+
print("-" * 10)
30+
31+
x.append('d')
32+
print(x)
33+
print("-" * 10)
34+
35+
x.__setitem__(4, 'e')
36+
print(x)
37+
print("-" * 10)
38+
39+
print(x[1])
40+
print(x.__getitem__(1))
41+
print("-" * 10)
42+
43+
print(x[4])
44+
print(x.__getitem__(4))

0 commit comments

Comments
 (0)