Programming with Python
Unit III
[Link]
Assistant Professor
Department of B Com(CA)
PSGR Krishnammal College for Women, Coimbatore
SYLLABUS-UNIT III
Object Oriented Programming: Classes and Objects –
Constructors – Destructors Getter and Setter Methods –
Encapsulations – Inheritance – Polymorphism – Abstract
Classes and Interfaces.
Abstract Classes in Python
• Designing Structured Code, Enforcing Interfaces,
and Promoting Scalability
Why Abstract Classes Matter
• Define templates for related classes
• Enforce a uniform structure
• Reduce code duplication and errors
• Support maintainability and scalability
• Promote clean architecture by separating
interface from implementation
Real-Life Analogy
• Abstract Class = Blueprint
• ✔ A blueprint cannot be used to build a house
directly
• ✔ But every house must follow the blueprint’s plan
• Similarly, abstract classes cannot be instantiated
but ensure that subclasses implement required
methods
Core Concepts
• Abstract Class: Cannot be instantiated directly
• Abstract Method: Must be implemented in child
classes
• Interface Definition: Specifies how objects behave
• Polymorphism: Allows objects to be used
interchangeably
The abc Module in Python
✔ Provides tools to create abstract classes and
methods
✔ Use ABC as the base class
✔ Use @abstractmethod to define abstract
methods
✔ Python simulates interfaces using abstract
classes
Syntax Breakdown
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def method_name(self):
pass
✔ Abstract classes derive from ABC
✔ Abstract methods must be implemented by
subclasses
Concrete Methods in Abstract Classes
✔ Abstract classes can contain fully implemented methods
✔ Subclasses inherit these methods unless overridden
Example:
class Shape(ABC):
@abstractmethod
def area(self):
pass
def describe(self):
print("This is a geometric shape")
Abstract Properties
✔Abstract methods can be properties
✔ Use @property and @abstractmethod decorators together
Example:
class Vehicle(ABC):
@property
@abstractmethod
def fuel_capacity(self):
pass
class Car(Vehicle):
@property
def fuel_capacity(self):
return 50
Example: Geometric Shapes
✔ Define abstract class Shape
✔ Implement concrete classes like Rectangle and Circle
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
Implementing Subclasses
class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height
def area(self):
return [Link] * [Link]
def perimeter(self):
return 2 * ([Link] + [Link])
✔ Subclasses must implement all abstract methods
Interface-Like Behavior
✔ Abstract classes define a consistent interface
✔ Allows polymorphism and reuse
Example:
def print_shape_details(shape):
print("Area:", [Link]())
print("Perimeter:", [Link]())
shapes = [Rectangle(3, 4), Circle(5)]
for s in shapes:
print_shape_details(s)
Preventing Instantiation
✔ Instantiating abstract classes raises TypeError
Example:
shape = Shape()
# TypeError: Can't instantiate abstract class Shape with abstract
methods area, perimeter
✔ Prevents incomplete implementations from being used
Abstract Classes vs Concrete Classes
Feature Abstract Class Concrete Class
Instantiation Cannot be instantiated Can be instantiated
May have abstract Must have full
Method Implementation
methods implementation
Define structure and Provide usable
Purpose
enforce rules implementations
Actual objects like
Examples Interfaces, templates
shapes, accounts
Abstract Classes and Polymorphism
✔ Allows writing code that works with different objects through a
common interface
✔ Encourages loose coupling between components
Example:
def calculate_area(shape: Shape):
return [Link]()
rectangle = Rectangle(10, 20)
circle = Circle(5)
print(calculate_area(rectangle))
print(calculate_area(circle))
When to Use Abstract Classes
✔ When you want a consistent interface for
unrelated classes
✔ When implementation specifics vary but the
structure remains the same
✔ When building reusable frameworks or libraries
✔ When enforcing certain behaviors in subclasses
Common Mistakes to Avoid
• Instantiating abstract classes directly
• Forgetting to implement abstract methods in subclasses
• Mixing too much logic in abstract classes
• Using abstract classes where simpler alternatives suffice
• Poor documentation leading to confusion
Best Practices
✔ Keep abstract classes focused and clean
✔ Document methods and properties clearly
✔ Implement all abstract methods in subclasses
✔ Use abstract properties to enforce attributes
✔ Write tests to ensure implementations are correct
Real-World Example: Banking System
✔ Use abstract classes to define transaction structure
Example:
class Account(ABC):
@abstractmethod
def deposit(self, amount):
pass
@abstractmethod
def withdraw(self, amount):
pass
class SavingsAccount(Account):
def __init__(self, balance=0):
[Link] = balance
def deposit(self, amount):
[Link] += amount
print(f"Deposited ${amount}")
def withdraw(self, amount):
if amount <= [Link]:
[Link] -= amount
print(f"Withdrew ${amount}")
else:
print("Insufficient funds")
Summary
✔ Abstract classes define structured templates for subclasses
✔ They enforce method signatures and attributes
✔ The abc module helps create abstract classes in Python
✔ Abstract classes support polymorphism and clean
architecture
✔ Following best practices leads to scalable, maintainable
designs
ASSESSMENT
[Link]