-
Notifications
You must be signed in to change notification settings - Fork 172
/
3.lsp.py
67 lines (51 loc) · 2.1 KB
/
3.lsp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
Liskov Substitution Principle
A sub-class must be substitutable for its super-class. The aim of this
principle is to ascertain that a sub-class can assume the place of its
super-class without errors. If the code finds itself checking the type of class
then, it must have violated this principle.
Let’s use our Animal example.
"""
def animal_leg_count(animals: list):
for animal in animals:
if isinstance(animal, Lion):
print(lion_leg_count(animal))
elif isinstance(animal, Mouse):
print(mouse_leg_count(animal))
elif isinstance(animal, Pigeon):
print(pigeon_leg_count(animal))
animal_leg_count(animals)
"""
To make this function follow the LSP principle, we will follow this LSP
requirements postulated by Steve Fenton:
If the super-class (Animal) has a method that accepts a super-class type
(Animal) parameter. Its sub-class(Pigeon) should accept as argument a
super-class type (Animal type) or sub-class type(Pigeon type). If the
super-class returns a super-class type (Animal). Its sub-class should return a
super-class type (Animal type) or sub-class type(Pigeon). Now, we can
re-implement animal_leg_count function:
"""
def animal_leg_count(animals: list):
for animal in animals:
print(animal.leg_count())
animal_leg_count(animals)
"""
The animal_leg_count function cares less the type of Animal passed, it just
calls the leg_count method. All it knows is that the parameter must be of an
Animal type, either the Animal class or its sub-class.
The Animal class now have to implement/define a leg_count method. And its
sub-classes have to implement the leg_count method:
"""
class Animal:
def leg_count(self):
pass
class Lion(Animal):
def leg_count(self):
pass
"""
When it’s passed to the animal_leg_count function, it returns the number of legs
a lion has.
You see, the animal_leg_count doesn’t need to know the type of Animal to return
its leg count, it just calls the leg_count method of the Animal type because by
contract a sub-class of Animal class must implement the leg_count function.
"""