Working with Abstract Classes and ABC in Python
By completing this lab, students will learn:
abc moduleBefore starting, students should know:
__init__()An abstract class is a parent class used as a blueprint. It contains one or more methods that must be completed in child classes.
Use abstract classes when multiple classes should follow the same structure.
Example:
sound()area()salary()Create a new Python file:
lab_abstract.py
At the top of the file, import:
ABC
abstractmethod
from Python abc module.
Create a class named:
Animal
Make this class inherit from ABC.
Inside Animal class, create a method named:
sound()
Rules:
@abstractmethodpassCreate a new class:
Dog
This class must inherit from Animal.
Now override sound() method.
Inside method display:
Dog barks
Create another child class:
Cat
This class also inherits from Animal.
Override sound() method.
Inside method display:
Cat meows
Create objects of:
Store in variables.
Example:
d
c
Call sound() method using both objects.
Expected behavior:
Run the file and observe output.
Try creating object of parent abstract class:
Animal()
Observe the error message.
Write in notebook:
Why did the error occur?
Create abstract class:
Shape
area()
Use constructor to receive:
Area formula:
length × width
Use constructor to receive:
Area formula:
Use math.pi
Create abstract class:
Employee
Create abstract method:
```python id=”q9qkq4” salary()
---
## Create Child Classes
### FullTimeEmployee
Return fixed salary.
### PartTimeEmployee
Return smaller salary.
---
## Final Steps
* Create both objects
* Print salaries
---
# Challenge Exercise
Create abstract class:
```python
Vehicle
Abstract method:
start()
Create child classes:
Each should print different start message.
Dog barks
Cat meows
Rectangle Area: ...
Circle Area: ...
Full Time Salary: ...
ABC?@abstractmethod?Students must submit:
| Task | Marks |
|---|---|
| Correct use of ABC | 3 |
| Correct inheritance | 3 |
| Correct methods | 4 |
| Output working | 5 |
| Code formatting | 2 |
| Total | 17 |