|
6 | 6 | # http://shop.oreilly.com/product/0636920040057.do |
7 | 7 | # Chapter 24 : Method Overloading - Extending and Providing |
8 | 8 |
|
9 | | -# This code is an example on how we can extend a method |
10 | | -#defined in a Parent class, in theChild class. |
11 | | - |
12 | | -# 1) We have defined `GetSetParent()` as an abstract class, |
13 | | -# and it has three methods,set_val(),get_val(), andshowdoc(). |
14 | | -# 2)GetSetInt() inherits fromGetSetParent() |
15 | | -# 3)GetSetInt() extends the parent'sset_val() method |
16 | | -# by it's ownset_val() method. It checks for the input, |
17 | | -# checks if it's an integer, and then calls theset_val() |
| 9 | +# This code is an example on how we can extend a method inherited by |
| 10 | +#a child class from theParent class. |
| 11 | + |
| 12 | +# 1) We have defined `MyClass()` as an abstract class, |
| 13 | +# and it has three methods,my_set_val(),my_get_val(), andprint_doc(). |
| 14 | +# 2)MyChildClass() inherits fromMyClass() |
| 15 | +# 3)MyChildClass() extends the parent'smy_set_val() method |
| 16 | +# by it's ownmy_set_val() method. It checks for the input, |
| 17 | +# checks if it's an integer, and then calls themy_set_val() |
18 | 18 | # method in the parent. |
19 | 19 |
|
20 | | -# 4) Theshowdoc() method in the Parent is an abstract method |
21 | | -# and hence should be implemented in the child classGetSetInt() |
| 20 | +# 4) Theprint_doc() method in the Parent is an abstract method |
| 21 | +# and hence should be implemented in the child classMyChildClass() |
22 | 22 |
|
23 | 23 |
|
24 | 24 | importabc |
25 | 25 |
|
26 | 26 |
|
27 | | -classGetSetParent(object): |
| 27 | +classMyClass(object): |
28 | 28 |
|
29 | 29 | __metaclass__=abc.ABCMeta |
30 | 30 |
|
31 | | -def__init__(self,value): |
32 | | -self.val=0 |
| 31 | +defmy_set_val(self,value): |
| 32 | +self.value=value |
33 | 33 |
|
34 | | -defset_val(self,value): |
35 | | -self.val=value |
36 | | - |
37 | | -defget_val(self): |
38 | | -returnself.val |
| 34 | +defmy_get_val(self): |
| 35 | +returnself.value |
39 | 36 |
|
40 | 37 | @abc.abstractmethod |
41 | | -defshowdoc(self): |
| 38 | +defprint_doc(self): |
42 | 39 | return |
43 | 40 |
|
44 | 41 |
|
45 | | -classGetSetInt(GetSetParent): |
| 42 | +classMyChildClass(MyClass): |
46 | 43 |
|
47 | | -defset_val(self,value): |
| 44 | +defmy_set_val(self,value): |
48 | 45 | ifnotisinstance(value,int): |
49 | 46 | value=0 |
50 | | -super(GetSetInt,self).set_val(self) |
| 47 | +super(MyChildClass,self).my_set_val(self) |
51 | 48 |
|
52 | | -defshowdoc(self): |
53 | | -print("GetSetInt object {0}), only accepts integer values".format( |
54 | | -id(self))) |
| 49 | +defprint_doc(self): |
| 50 | +print("Documentation for MyChild Class") |
55 | 51 |
|
| 52 | +my_instance=MyChildClass() |
| 53 | +my_instance.my_set_val(100) |
| 54 | +print(my_instance.my_get_val()) |
| 55 | +print(my_instance.print_doc()) |
56 | 56 |
|