Bank Marketing OOP Project
Bank Marketing Campaign System
This project connects Object-Oriented Programming to a realistic banking workflow.
Business Problem
A bank wants to identify customers for a premium deposit campaign. A customer qualifies when:
- Age is between 21 and 65
- Account balance is at least ₹50,000
- Customer has no credit default
We will load customer data, create objects, apply reusable eligibility rules, contact selected customers, and generate a campaign report.
OOP Roadmap
| OOP Concept | Banking Implementation |
|---|---|
| Class and Object | Customer, Campaign, ContactRecord |
| Encapsulation | Private-style _balance with controlled deposit/withdraw methods |
| Abstraction | EligibilityRule abstract class |
| Inheritance | Age, Balance and Default rules inherit from EligibilityRule |
| Polymorphism | Every rule responds to the same evaluate() method |
| Composition | Eligibility engine contains multiple rules |
| Dependency Injection | Service receives a repository and rule engine |
| Class Method | Create a customer from a dictionary |
| Static Method | Validate a phone number |
| Property | Read balance safely |
| Exception Handling | Clear validation and insufficient-balance errors |
Custom Exceptions
Specific exception classes communicate exactly what went wrong. They are clearer than raising a general Exception.
class BankCampaignError(Exception):
"""Base exception for this application."""
class ValidationError(BankCampaignError):
"""Raised when input data is invalid."""
class InsufficientBalanceError(BankCampaignError):
"""Raised when withdrawal is greater than balance."""
BankCampaignError is the parent exception.ValidationError is raised for invalid age, name, phone, etc.InsufficientBalanceError is raised when withdrawal amount is greater than available balance.
Customer Class — Encapsulation
A class is a blueprint; an object is one real customer created from that blueprint.
_balance is not changed directly. deposit() and withdraw() protect the object's state. @property gives controlled read access.
@dataclass
class Customer:
customer_id: int
name: str
age: int
job: str
phone: str
has_default: bool = False
_balance: float = field(default=0.0, repr=False)
def __post_init__(self):
if self.customer_id <= 0:
raise ValidationError("Customer ID must be positive")
if not self.name.strip():
raise ValidationError("Name cannot be empty")
if not 18 <= self.age <= 100:
raise ValidationError("Age must be between 18 and 100")
if self._balance < 0:
raise ValidationError("Opening balance cannot be negative")
if not self.is_valid_phone(self.phone):
raise ValidationError("Phone must contain exactly 10 digits")
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValidationError("Deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValidationError("Withdrawal must be positive")
if amount > self._balance:
raise InsufficientBalanceError("Insufficient balance")
self._balance -= amount
@staticmethod
def is_valid_phone(phone):
return str(phone).isdigit() and len(str(phone)) == 10
@classmethod
def from_dict(cls, row):
return cls(
int(row["customer_id"]), row["name"], int(row["age"]),
row["job"], str(row["phone"]),
str(row["has_default"]).lower() == "yes",
float(row["balance"])
)
@dataclass automatically creates __init__(), __repr__() and __eq__()._balance is treated as an internal variable (encapsulation).@property allows reading balance safely.@staticmethod validates phone without needing an object.@classmethod creates a Customer from a dictionary.
Create and operate on an object
asha = Customer(1, "Asha", 32, "Engineer", "9876543210", False, 80_000)
print("Opening balance:", asha.balance)
asha.deposit(5_000)
asha.withdraw(10_000)
print("Closing balance:", asha.balance)
print("Valid phone?", Customer.is_valid_phone(asha.phone))
Opening balance: 80000 Closing balance: 75000 Valid phone? True
sundar = Customer(2, "Sundar", 35, "Data Scientist", "9535255446", False, 90_000)
print("Opening balance:", sundar.balance)
sundar.deposit(10_000)
sundar.withdraw(20_000)
print("Closing balance:", sundar.balance)
print("Valid phone?", Customer.is_valid_phone(sundar.phone))
Opening balance: 90000 Closing balance: 80000 Valid phone? True
Campaign and Contact Models
Each class has one responsibility. Enum prevents inconsistent status values such as Success, successful, and Done.
@dataclass(frozen=True)
class Campaign:
campaign_id: int
name: str
offer: str
class ContactStatus(Enum):
SUCCESS = "success"
FAILED = "failed"
NO_RESPONSE = "no_response"
@dataclass
class ContactRecord:
customer_id: int
campaign_id: int
status: ContactStatus
contacted_at: datetime = field(default_factory=datetime.now)
Campaign is frozen (immutable).ContactStatus uses Enum for fixed allowed values.ContactRecord stores the result of contacting a customer.
Abstraction
EligibilityRule is an abstract contract. It says every rule must implement evaluate(customer).
The child classes inherit the contract and provide their own decision logic.
from abc import ABC, abstractmethod
@dataclass(frozen=True)
class RuleResult:
passed: bool
reason: str
class EligibilityRule(ABC):
@abstractmethod
def evaluate(self, customer):
pass
ABC means Abstract Base Class.@abstractmethod forces every child class to implement the evaluate() method.
Inheritance — Concrete Rules
Age, Balance and Default rules inherit from EligibilityRule and implement their own evaluate() method.
class AgeRule(EligibilityRule):
def __init__(self, minimum=21, maximum=65):
self.minimum, self.maximum = minimum, maximum
def evaluate(self, customer):
passed = self.minimum <= customer.age <= self.maximum
return RuleResult(passed, "Age accepted" if passed else "Age outside range")
class BalanceRule(EligibilityRule):
def __init__(self, minimum_balance=50_000):
self.minimum_balance = minimum_balance
def evaluate(self, customer):
passed = customer.balance >= self.minimum_balance
return RuleResult(passed, "Balance accepted" if passed else "Balance too low")
class NoDefaultRule(EligibilityRule):
def evaluate(self, customer):
passed = not customer.has_default
return RuleResult(passed, "No default" if passed else "Customer has default")
EligibilityRule and provides its own implementation of evaluate().
Polymorphism
The engine calls the same evaluate() method on different objects. Python automatically executes the correct child-class version — this is Polymorphism.
@dataclass
class EligibilityDecision:
eligible: bool
results: list
class EligibilityEngine:
def __init__(self, rules):
self.rules = rules
def check(self, customer):
results = [rule.evaluate(customer) for rule in self.rules]
return EligibilityDecision(
all(result.passed for result in results),
results
)
rule.evaluate(customer) on every rule.It does not care whether the rule is checking Age, Balance or Default status.
Python automatically runs the correct version of
evaluate() based on the actual object type.This is Polymorphism.
Because of polymorphism, we can easily add a new rule in the future (for example OccupationRule) without changing the engine code.
Composition
The engine has a collection of rules. This is called Composition.
Composition means one object contains other objects.
engine = EligibilityEngine([
AgeRule(),
BalanceRule(50_000),
NoDefaultRule()
])
decision = engine.check(asha)
print("Eligible:", decision.eligible)
for result in decision.results:
print("-", result.reason)
Eligible: True - Age accepted - Balance accepted - No default
Repository Abstraction
The business service should not care whether data comes from a list, CSV, MySQL, or an API.
A repository contract separates data access from business logic.
class CustomerRepository(ABC):
@abstractmethod
def get_all(self):
pass
class InMemoryCustomerRepository(CustomerRepository):
def __init__(self, customers):
self._customers = customers
def get_all(self):
return list(self._customers)
CSVCustomerRepository or MySQLCustomerRepository without changing the service code.
Service Layer — Dependency Injection
CampaignService receives its dependencies through the constructor. This is called Dependency Injection.
@dataclass
class CampaignReport:
total_customers: int
eligible_customers: int
contacted: int
successful: int
failed: int
no_response: int
@property
def conversion_rate(self):
return 0 if self.contacted == 0 else self.successful / self.contacted * 100
class CampaignService:
def __init__(self, repository, engine):
self.repository = repository
self.engine = engine
self.records = []
def evaluate_all(self):
return [(customer, self.engine.check(customer))
for customer in self.repository.get_all()]
def find_eligible_customers(self):
return [(c, d) for c, d in self.evaluate_all() if d.eligible]
def record_contact(self, customer, campaign, status):
record = ContactRecord(customer.customer_id, campaign.campaign_id, status)
self.records.append(record)
return record
def build_report(self):
counts = {status: 0 for status in ContactStatus}
for record in self.records:
counts[record.status] += 1
return CampaignReport(
len(self.repository.get_all()),
len(self.find_eligible_customers()),
len(self.records),
counts[ContactStatus.SUCCESS],
counts[ContactStatus.FAILED],
counts[ContactStatus.NO_RESPONSE]
)
Run the End-to-End Campaign
raw_customers = [
{"customer_id": 1, "name": "Asha", "age": 32, "job": "Engineer", "phone": "9876543210", "has_default": "no", "balance": 85000},
{"customer_id": 2, "name": "Rahul", "age": 19, "job": "Student", "phone": "9876543211", "has_default": "no", "balance": 12000},
{"customer_id": 3, "name": "Meera", "age": 45, "job": "Teacher", "phone": "9876543212", "has_default": "no", "balance": 65000},
{"customer_id": 4, "name": "Arjun", "age": 38, "job": "Business Owner", "phone": "9876543213", "has_default": "yes", "balance": 140000},
{"customer_id": 5, "name": "Lakshmi", "age": 58, "job": "Manager", "phone": "9876543214", "has_default": "no", "balance": 95000},
{"customer_id": 6, "name": "Ravi", "age": 68, "job": "Retired", "phone": "9876543215", "has_default": "no", "balance": 170000},
]
customers = [Customer.from_dict(row) for row in raw_customers]
repository = InMemoryCustomerRepository(customers)
engine = EligibilityEngine([AgeRule(21, 65), BalanceRule(50_000), NoDefaultRule()])
service = CampaignService(repository, engine)
campaign = Campaign(101, "Premium Savings", "7.5% promotional fixed deposit")
for customer, decision in service.evaluate_all():
reasons = "; ".join(r.reason for r in decision.results if not r.passed)
print(f"{customer.name:10} | {'ELIGIBLE' if decision.eligible else 'REJECTED':8} | {reasons or 'All rules passed'}")
Asha | ELIGIBLE | All rules passed Rahul | REJECTED | Age outside range; Balance too low Meera | ELIGIBLE | All rules passed Arjun | REJECTED | Customer has default Lakshmi | ELIGIBLE | All rules passed Ravi | REJECTED | Age outside range
Key Takeaway
OOP is not merely creating classes. It organizes business responsibilities so that new rules, data sources, and campaign channels can be added with minimal changes to existing code.
Interview Questions
- Why is
_balanceencapsulated? - What is the difference between Abstraction and Encapsulation here?
- Where does method overriding happen?
- How does Polymorphism remove long
if/eliflogic? - Why is the repository useful when moving from a list to MySQL?
Assignments
- Add an
OccupationRulethat excludes selected occupations. - Add a
PreviousCampaignRule. - Create
CSVCustomerRepositoryusing Python'scsvmodule. - Create
EmailCampaignandSMSCampaignsubclasses. - Export the campaign report to CSV.
Bank Marketing Campaign — End-to-End OOP Project
A complete real-world project covering Encapsulation, Abstraction, Inheritance, Polymorphism and more.
Select any topic from the left sidebar to begin.
Start Learning →
