OOP & Advanced Python

Bank Marketing OOP Project

01 · Business Problem File · Bank OOP · 1 of 13

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.

02 · OOP Roadmap File · Bank OOP · 2 of 13

OOP Roadmap

OOP ConceptBanking Implementation
Class and ObjectCustomer, Campaign, ContactRecord
EncapsulationPrivate-style _balance with controlled deposit/withdraw methods
AbstractionEligibilityRule abstract class
InheritanceAge, Balance and Default rules inherit from EligibilityRule
PolymorphismEvery rule responds to the same evaluate() method
CompositionEligibility engine contains multiple rules
Dependency InjectionService receives a repository and rule engine
Class MethodCreate a customer from a dictionary
Static MethodValidate a phone number
PropertyRead balance safely
Exception HandlingClear validation and insufficient-balance errors
03 · Custom Exceptions File · Bank OOP · 3 of 13

Custom Exceptions

Specific exception classes communicate exactly what went wrong. They are clearer than raising a general Exception.

Python
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.
04 · Customer Class File · Bank OOP · 4 of 13

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.

Python
@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

Python
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))
Output
Opening balance: 80000
Closing balance: 75000
Valid phone? True
Methods combine data and behaviour inside one object.
Python
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))
Output
Opening balance: 90000
Closing balance: 80000
Valid phone? True
05 · Campaign Models File · Bank OOP · 5 of 13

Campaign and Contact Models

Each class has one responsibility. Enum prevents inconsistent status values such as Success, successful, and Done.

Python
@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.
06 · Abstraction Explained File · Bank OOP · 6 of 13

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.

Python
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.
07 · Inheritance in Rules File · Bank OOP · 7 of 13

Inheritance — Concrete Rules

Age, Balance and Default rules inherit from EligibilityRule and implement their own evaluate() method.

Python
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")
Each rule inherits from EligibilityRule and provides its own implementation of evaluate().
08 · Polymorphism Explained File · Bank OOP · 8 of 13

Polymorphism

The engine calls the same evaluate() method on different objects. Python automatically executes the correct child-class version — this is Polymorphism.

Python
@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
        )
Notice that the engine simply calls 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.

09 · Composition & Engine File · Bank OOP · 9 of 13

Composition

The engine has a collection of rules. This is called Composition.

Composition means one object contains other objects.

Python
engine = EligibilityEngine([
    AgeRule(),
    BalanceRule(50_000),
    NoDefaultRule()
])

decision = engine.check(asha)
print("Eligible:", decision.eligible)
for result in decision.results:
    print("-", result.reason)
Output
Eligible: True
- Age accepted
- Balance accepted
- No default
The engine contains multiple rule objects and runs them one by one.
10 · Repository Pattern File · Bank OOP · 10 of 13

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.

Python
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)
Later we can create CSVCustomerRepository or MySQLCustomerRepository without changing the service code.
11 · Service Layer File · Bank OOP · 11 of 13

Service Layer — Dependency Injection

CampaignService receives its dependencies through the constructor. This is called Dependency Injection.

Python
@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]
        )
The service depends on a repository and an engine. This makes the code flexible and easy to test.
12 · Run the Campaign File · Bank OOP · 12 of 13

Run the End-to-End Campaign

Python
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'}")
Output
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
Only customers who pass Age, Balance and No-Default rules are marked ELIGIBLE.
13 · Tests & Takeaways File · Bank OOP · 13 of 13

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

  1. Why is _balance encapsulated?
  2. What is the difference between Abstraction and Encapsulation here?
  3. Where does method overriding happen?
  4. How does Polymorphism remove long if/elif logic?
  5. Why is the repository useful when moving from a list to MySQL?

Assignments

  1. Add an OccupationRule that excludes selected occupations.
  2. Add a PreviousCampaignRule.
  3. Create CSVCustomerRepository using Python's csv module.
  4. Create EmailCampaign and SMSCampaign subclasses.
  5. Export the campaign report to CSV.
Home Bank Marketing OOP Project

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 →