Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f2883f1

Browse files
committed
Add Abstract Class examples
1 parent 8cc900e commit f2883f1

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,4 @@ files, and the full tutorial for each collection of code is available below.
3434
27. [Instance Methods And Attributes](https://vegibit.com/python-instance-methods-and-attributes/)
3535
28. [How To Use type() And isinstance()](https://vegibit.com/how-to-use-type-and-isinstance-in-python/)
3636
29. [Basic Python Inheritance](https://vegibit.com/basic-python-inheritance/)
37+
30. [Abstract Base Classes](https://vegibit.com/python-abstract-base-classes/)

abstractclass.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Simple Class With Inheritance
2+
class Vehicle:
3+
def __init__(self):
4+
super().__init__()
5+
6+
def go_forward(self):
7+
print('Driving forward.')
8+
9+
10+
class Car(Vehicle):
11+
def __init__(self):
12+
super().__init__()
13+
14+
15+
class Truck(Vehicle):
16+
def __init__(self):
17+
super().__init__()
18+
19+
20+
vehicle1 = Vehicle()
21+
22+
car1 = Car()
23+
car1.go_forward()
24+
25+
truck1 = Truck()
26+
truck1.go_forward()
27+
28+
# Adding Abstract Base Class
29+
from abc import ABC, abstractmethod
30+
31+
32+
class Vehicle(ABC):
33+
def __init__(self):
34+
super().__init__()
35+
36+
@abstractmethod
37+
def go_forward(self):
38+
pass
39+
40+
41+
# Adding A Subclass
42+
class Car(Vehicle):
43+
def __init__(self, press_accelerator):
44+
super().__init__()
45+
self.press_accelerator = press_accelerator
46+
47+
def go_forward(self):
48+
if self.press_accelerator:
49+
print('Driving forward')
50+
else:
51+
print('Press the accelerator to drive forward')
52+
53+
54+
car1 = Car(True)
55+
car1.go_forward()
56+
57+
58+
# A Second Subclass
59+
class Truck(Vehicle):
60+
def __init__(self, press_accelerator):
61+
super().__init__()
62+
self.press_accelerator = press_accelerator
63+
64+
def go_forward(self):
65+
if self.press_accelerator:
66+
print('Driving forward')
67+
else:
68+
print('Press the accelerator to drive forward')
69+
70+
71+
truck1 = Truck(False)
72+
truck1.go_forward()
73+
74+
truck2 = Truck(True)
75+
truck2.go_forward()

0 commit comments

Comments
 (0)