-
Notifications
You must be signed in to change notification settings - Fork 0
/
45_abstract_classes.py
76 lines (45 loc) · 2.03 KB
/
45_abstract_classes.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
68
69
70
71
72
73
74
75
76
# An abstract class prevents a user from creating an object of that class (Just a template, a ghost class)
# It compels a user to override abstract methods in a child class
# abstract class = class which contains one or more abstract methods
# abstract method = method that has a declaration but does not have an implementation
class Vehicle:
def go(self):
pass
class Car(Vehicle):
def go(self): # the go(self) function is being overridden and adding our own implementation
print("You drive the car")
class Motorcycle(Vehicle):
def go(self): # the go(self) function is being overridden and adding our own implementation
print("You ride the motorcycle")
vehicle = Vehicle()
car = Car()
motorcycle = Motorcycle()
vehicle.go() # this will do nothing it has not been implemented but has been declared
car.go()
motorcycle.go()
# For example, we want a user to create an object that is not of vehicle class since its too generic
# So we turn the vehicle class into an abstract class
# We do the following
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod # this is done before every method. Prevents us from creating this object
def go(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def go(self): # the go(self) function is being overridden and adding our own implementation
print("You drive the car")
def stop(self):
print("You stop the car")
class Motorcycle(Vehicle):
def go(self): # the go(self) function is being overridden and adding our own implementation
print("You ride the motorcycle")
# children classes should not be missing an implementations of any methods they inherit
def stop(self):
print("You stop the motorcycle")
vehicle = Vehicle() # TypeError: can't instantiate abstract class Vehicle with abstract method go.
car = Car()
motorcycle = Motorcycle()
# the children classes will inherit the abstract method. This means they NEED to override the abstract method