Example Project: Analyzing Real-Life Data with Python Classes

Project: Employee Management System

  1. Class Definition: Define classes for Employee, Manager, and Department.
  2. Attributes and Methods: Load and store employee data, calculate salaries, and manage departments.
  3. Inheritance: Use inheritance to create specialized employee types.
Python Implementation
import pandas as pd

class Employee:
    def __init__(self, emp_id, name, base_salary):
        self.emp_id = emp_id
        self.name = name
        self.base_salary = base_salary

    def get_annual_salary(self):
        return self.base_salary * 12

class Manager(Employee):
    def __init__(self, emp_id, name, base_salary, bonus):
        super().__init__(emp_id, name, base_salary)
        self.bonus = bonus

    def get_annual_salary(self):
        return super().get_annual_salary() + self.bonus

class Department:
    def __init__(self, name):
        self.name = name
        self.employees = []

    def add_employee(self, employee):
        self.employees.append(employee)

    def get_total_salary(self):
        return sum(emp.get_annual_salary() for emp in self.employees)

# Load employee data
data = {
    'emp_id': [1, 2, 3],
    'name': ['Alice', 'Bob', 'Charlie'],
    'base_salary': [5000, 7000, 6000],
    'bonus': [2000, 0, 1500]
}
df = pd.DataFrame(data)

# Create department and add employees
dept = Department('HR')
for index, row in df.iterrows():
    if row['bonus'] > 0:
        emp = Manager(row['emp_id'], row['name'], row['base_salary'], row['bonus'])
    else:
        emp = Employee(row['emp_id'], row['name'], row['base_salary'])
    dept.add_employee(emp)

# Calculate total salary
print(f"Total Salary in {dept.name} Department: {dept.get_total_salary()}")
  • Python: Easier syntax, automatic memory management, dynamic typing, and simpler inheritance model.
  • C++: More control over memory management, explicit typing, more complex but powerful features like operator overloading, virtual functions, and precise access control.

Each language has its strengths and is chosen based on the requirements of the project. Python is often preferred for rapid development and ease of use, while C++ is chosen for performance-critical applications and fine-grained control over system resources.

Project:-

Statement-to create a Banking Data universe ,using OOPs in Python Bank will be a class and different banks will be object. Want to add a new bank in universe will create a new object. Sub classes can be Retail Banking, Wholesome Banking, Deposits etc. Please create a architecture and python script for it. also please think and include DBMS , Big data framework and other operation to be includded in this framework.

Sample-

To create a comprehensive banking data universe using object-oriented programming (OOP) in Python, we need to define a well-structured class architecture that can encapsulate various banking operations. Here’s an approach to achieve this:

  1. Class Definitions:
    • Bank: Base class for all banks.
    • RetailBanking: Subclass for retail banking operations.
    • WholesaleBanking: Subclass for wholesale banking operations.
    • Deposits: Subclass for deposit operations.
  2. Database and Big Data Integration:
    • Integration with a relational database (e.g., MySQL, PostgreSQL) to store structured data.
    • Integration with a Big Data framework (e.g., Hadoop, Spark) for large-scale data processing.

Class Architecture

  1. Bank Class:
    • Attributes: bank name, ID, and other general details.
    • Methods: add bank, get bank details, etc.
  2. RetailBanking Class:
    • Attributes: specific to retail banking.
    • Methods: personal loans, savings accounts, etc.
  3. WholesaleBanking Class:
    • Attributes: specific to wholesale banking.
    • Methods: corporate loans, trade finance, etc.
  4. Deposits Class:
    • Attributes: deposit types, rates, etc.
    • Methods: create deposit, get deposit details, etc.

Example Python Script

class Bank:
    bank_count = 0
    
    def __init__(self, name):
        self.id = Bank.bank_count
        self.name = name
        self.retail_banking = None
        self.wholesale_banking = None
        self.deposits = None
        Bank.bank_count += 1
    
    def add_retail_banking(self):
        self.retail_banking = RetailBanking(self)
    
    def add_wholesale_banking(self):
        self.wholesale_banking = WholesaleBanking(self)
    
    def add_deposits(self):
        self.deposits = Deposits(self)
    
    def get_details(self):
        details = {
            'ID': self.id,
            'Name': self.name,
            'Retail Banking': self.retail_banking is not None,
            'Wholesale Banking': self.wholesale_banking is not None,
            'Deposits': self.deposits is not None
        }
        return details

class RetailBanking:
    def __init__(self, bank):
        self.bank = bank
        self.services = ['Personal Loans', 'Savings Accounts']
    
    def get_services(self):
        return self.services

class WholesaleBanking:
    def __init__(self, bank):
        self.bank = bank
        self.services = ['Corporate Loans', 'Trade Finance']
    
    def get_services(self):
        return self.services

class Deposits:
    def __init__(self, bank):
        self.bank = bank
        self.types = ['Fixed Deposit', 'Recurring Deposit']
    
    def get_deposit_types(self):
        return self.types

# Adding a new bank to the universe
bank_universe = []

def add_bank(name):
    bank = Bank(name)
    bank.add_retail_banking()
    bank.add_wholesale_banking()
    bank.add_deposits()
    bank_universe.append(bank)
    return bank

# Example of usage
hdfc_bank = add_bank("HDFC Bank")
icici_bank = add_bank("ICICI Bank")

for bank in bank_universe:
    print(bank.get_details())

# Output
# {'ID': 0, 'Name': 'HDFC Bank', 'Retail Banking': True, 'Wholesale Banking': True, 'Deposits': True}
# {'ID': 1, 'Name': 'ICICI Bank', 'Retail Banking': True, 'Wholesale Banking': True, 'Deposits': True}

Integration with DBMS and Big Data Framework

To integrate with a database and a big data framework, you can use libraries such as SQLAlchemy for database operations and PySpark for big data processing.

Database Integration Example

from sqlalchemy import create_engine, Column, Integer, String, Sequence
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Setting up the database
Base = declarative_base()
engine = create_engine('sqlite:///banking_universe.db')
Session = sessionmaker(bind=engine)
session = Session()

# Defining the Bank model
class BankModel(Base):
    __tablename__ = 'banks'
    id = Column(Integer, Sequence('bank_id_seq'), primary_key=True)
    name = Column(String(50))

# Creating the table
Base.metadata.create_all(engine)

# Adding banks to the database
def add_bank_to_db(name):
    bank = BankModel(name=name)
    session.add(bank)
    session.commit()

# Example of adding a bank to the database
add_bank_to_db("HDFC Bank")
add_bank_to_db("ICICI Bank")

# Querying the database
for bank in session.query(BankModel).all():
    print(bank.name)

Big Data Framework Integration Example

from pyspark.sql import SparkSession

# Initialize Spark session
spark = SparkSession.builder 
    .appName("BankingDataUniverse") 
    .getOrCreate()

# Sample data
data = [
    ("HDFC Bank", "Retail", 1000),
    ("ICICI Bank", "Wholesale", 2000)
]

# Creating DataFrame
columns = ["BankName", "BankType", "Transactions"]
df = spark.createDataFrame(data, columns)

# Performing operations
df.show()
df.groupBy("BankType").sum("Transactions").show()

# Stop the Spark session
spark.stop()

This architecture and implementation provide a foundation for a banking data universe using OOP in Python. It includes:

  • Class Structure: Bank, RetailBanking, WholesaleBanking, and Deposits.
  • DBMS Integration: Using SQLAlchemy for database operations.
  • Big Data Framework Integration: Using PySpark for large-scale data processing.

This setup can be expanded and customized based on specific requirements, such as adding more methods and functionalities to handle complex banking operations, and integrating with other technologies as needed.

Other Approach involving Metaclass can be:-

Creating a comprehensive banking data universe using OOP in Python involves designing a flexible architecture that includes classes for banks, various banking operations, and data management. The architecture can incorporate DBMS for data storage, a big data framework for handling large datasets, and metaclasses for managing the overall structure.

Architecture

  1. Banking Universe:
    • A metaclass to manage all banks.
    • A base Bank class.
    • Subclasses for different types of banking operations (Retail Banking, Wholesale Banking, Deposits, etc.).
    • Integration with DBMS and Big Data frameworks for data management and operations.
  2. Components:
    • Metaclass: BankingMeta to handle bank registration.
    • Base Class: Bank.
    • Subclasses: RetailBanking, WholesaleBanking, Deposits, etc.
    • Database Integration: Use SQLite for DBMS.
    • Big Data Integration: Placeholder for integrating with frameworks like Hadoop/Spark.

Python Script

import sqlite3

# Metaclass to manage all banks
class BankingMeta(type):
    _banks = {}

    def __init__(cls, name, bases, attrs):
        super().__init__(name, bases, attrs)
        if not cls.__name__ == 'Bank':
            BankingMeta._banks[cls.__name__] = cls

    @classmethod
    def get_bank(cls, name):
        return cls._banks.get(name)

    @classmethod
    def register_bank(cls, bank_name, bank_obj):
        cls._banks[bank_name] = bank_obj

# Base Bank class
class Bank(metaclass=BankingMeta):
    def __init__(self, name):
        self.name = name
        self.connect_db()

    def connect_db(self):
        self.conn = sqlite3.connect(f'{self.name}.db')
        self.cursor = self.conn.cursor()
        self.setup_db()

    def setup_db(self):
        raise NotImplementedError

    def close_db(self):
        self.conn.close()

# Subclass for Retail Banking
class RetailBanking(Bank):
    def setup_db(self):
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS retail_accounts (
                account_id INTEGER PRIMARY KEY,
                account_holder TEXT,
                balance REAL
            )
        ''')
        self.conn.commit()

    def add_account(self, account_holder, balance):
        self.cursor.execute('''
            INSERT INTO retail_accounts (account_holder, balance)
            VALUES (?, ?)
        ''', (account_holder, balance))
        self.conn.commit()

# Subclass for Wholesale Banking
class WholesaleBanking(Bank):
    def setup_db(self):
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS wholesale_accounts (
                account_id INTEGER PRIMARY KEY,
                company_name TEXT,
                credit_limit REAL
            )
        ''')
        self.conn.commit()

    def add_account(self, company_name, credit_limit):
        self.cursor.execute('''
            INSERT INTO wholesale_accounts (company_name, credit_limit)
            VALUES (?, ?)
        ''', (company_name, credit_limit))
        self.conn.commit()

# Subclass for Deposits
class Deposits(Bank):
    def setup_db(self):
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS deposits (
                deposit_id INTEGER PRIMARY KEY,
                depositor TEXT,
                amount REAL
            )
        ''')
        self.conn.commit()

    def add_deposit(self, depositor, amount):
        self.cursor.execute('''
            INSERT INTO deposits (depositor, amount)
            VALUES (?, ?)
        ''', (depositor, amount))
        self.conn.commit()

# Function to add a new bank
def add_new_bank(bank_type, bank_name):
    bank_class = BankingMeta.get_bank(bank_type)
    if bank_class:
        bank_obj = bank_class(bank_name)
        BankingMeta.register_bank(bank_name, bank_obj)
        print(f"New bank '{bank_name}' of type '{bank_type}' added to the universe.")
    else:
        print(f"Bank type '{bank_type}' not recognized.")

# Usage example
if __name__ == "__main__":
    add_new_bank("RetailBanking", "RetailBank1")
    add_new_bank("WholesaleBanking", "WholesaleBank1")
    add_new_bank("Deposits", "DepositBank1")

    # Interact with the banks
    retail_bank = BankingMeta.get_bank("RetailBank1")
    if retail_bank:
        retail_bank.add_account("John Doe", 1000.00)

    wholesale_bank = BankingMeta.get_bank("WholesaleBank1")
    if wholesale_bank:
        wholesale_bank.add_account("ABC Corp", 50000.00)

    deposit_bank = BankingMeta.get_bank("DepositBank1")
    if deposit_bank:
        deposit_bank.add_deposit("Jane Doe", 5000.00)

Explanation

  1. Metaclass BankingMeta:
    • Manages all bank classes and their instances.
    • Provides methods to get and register banks.
  2. Base Class Bank:
    • Defines the basic structure for a bank, including connecting to a database.
    • Uses SQLite for simplicity.
  3. Subclasses (RetailBanking, WholesaleBanking, Deposits):
    • Each subclass implements specific banking operations.
    • Each subclass has its own method to set up the database schema and add data.
  4. Function add_new_bank:
    • Adds new bank instances based on the bank type and name.
    • Registers the new bank in the banking universe.
  5. Usage Example:
    • Demonstrates how to add new banks and interact with them.

Future Enhancements

  1. Big Data Integration:
    • Integrate with Hadoop or Spark for large-scale data processing.
    • Use PySpark or similar frameworks to handle big data operations.
  2. Advanced DBMS:
    • Replace SQLite with more advanced DBMS like PostgreSQL or MySQL.
    • Implement advanced querying and data manipulation.
  3. Additional Features:
    • Implement more banking operations and subclasses.
    • Add functionalities for transactions, loans, interest calculations, etc.
    • Enhance security and user authentication mechanisms.

This architecture provides a flexible and scalable foundation for creating a comprehensive banking data universe in Python. By leveraging OOP principles, it ensures maintainability and ease of extension for future enhancements.


Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Pages ( 7 of 7 ): « Previous1 ... 56 7

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading