File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
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 ))
You can’t perform that action at this time.
0 commit comments