Summary - Abstract classes
- Python course
- Intermediate
- Lesson 52/116
- 5 min
Combine ABC and Protocol to write a payment system.
Summary - Abstract classes
In this group we covered abstract class (ABC) basics, required methods with @abstractmethod, abstract property, structural conformance with Protocol, and the ABC vs Protocol difference.
ABC enforces inheritance; abstract methods and abstract properties are filled by the subclass. Protocol provides structural conformance without inheritance. Now we'll write an example that combines these.
Practice Combined summary example
Start with from abc import ABC, abstractmethod. Define the abstract class Shape(ABC); inside, use @property and @abstractmethod with def area(self): and pass. Define class Rectangle(Shape):; write def __init__(self, w, h): with self.w = w, self.h = h. Add @property with def area(self): and return self.w * self.h. Finally create r = Rectangle(3, 4) and print with print(r.area).
Starter code
# Write the Shape abstract class and the Rectangle subclassSample solution
# Write the Shape abstract class and the Rectangle subclass
from abc import ABC, abstractmethod
class Shape(ABC):
@property
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
@property
def area(self):
return self.w * self.h
r = Rectangle(3, 4)
print(r.area)Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which combination is wrong?
- @property + @abstractmethod stacked
- ABC + @abstractmethod
- @runtime_checkable + Protocol
- @abstractmethod + Protocol base Correct answer
Explanation: Protocol does not use abstractmethod.
2 Match the concepts
| Term | Meaning |
|---|---|
ABC |
Inheritance required |
@abstractmethod |
Required method |
@property + @abstractmethod |
Abstract property |
Protocol |
Structural conformance |
3 Rectangle property line
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
____
def area(self):
return self.w * self.h
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
@property
def area(self):
return self.w * self.h
Explanation: The subclass fills area with @property.
4 Match the abstract class parts
| Term | Meaning |
|---|---|
ABC |
Abstract base |
@abstractmethod |
Required method |
@property |
Subclass fill |
r.area |
Computation call |