0% found this document useful (0 votes)
2 views11 pages

5th Module Plc

The document provides an overview of object-oriented programming concepts, including classes, objects, attributes, and methods, with practical applications in automotive and banking domains. It covers topics like mutable objects, copying, pure functions, and operator overloading, along with examples and use cases. Additionally, it discusses the importance of encapsulation, abstraction, inheritance, and polymorphism in designing robust systems.

Uploaded by

gtshadow2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

5th Module Plc

The document provides an overview of object-oriented programming concepts, including classes, objects, attributes, and methods, with practical applications in automotive and banking domains. It covers topics like mutable objects, copying, pure functions, and operator overloading, along with examples and use cases. Additionally, it discusses the importance of encapsulation, abstraction, inheritance, and polymorphism in designing robust systems.

Uploaded by

gtshadow2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1.

Classes and Objects: Programmer-Defined Types


✅ What it is?
 A class is a blueprint for creating objects (instances).
 An object is a collection of data (attributes) and behaviors (methods).
 Programmer-defined types allow you to model real-world entities.

📍When and Where to Apply?


 When built-in types (like int, list) are insufficient to represent domain-specific data
models.
 In domains requiring encapsulation of related data and behavior like:
 Automotive: Engine, Sensor, Vehicle
 Banking: Account, Customer, Transaction

🛠️How to Apply?

class Customer:
pass

cust1 = Customer()

2. Attributes
✅ What it is?
 Attributes are variables that belong to an object or class.

📍When and Where to Apply?


 Used to represent state or properties of an object.
 Automotive: speed, fuel_level, rpm for Car object.

 Banking: balance, account_number for BankAccount.

🛠️How to Apply?

class Car:
def __init__(self, make, speed):
self.make = make
self.speed = speed

my_car = Car("Volvo", 80)


print(my_car.make, my_car.speed)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


3. Rectangles (Example Class)
✅ What it is?
 An example from the book for modeling geometric data using objects.

📍When and Where to Apply?


 This can model screen areas, sensor ranges, or bank branches' layout zones.

🛠️How to Apply?

class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

r = Rectangle(5, 10)
print(r.width * r.height)

4. Instances as Return Values


✅ What it is?
 Functions can create and return instances (objects) of classes.

📍When and Where to Apply?


 To encapsulate logic inside functions that produce customized objects.
 Automotive: A create_vehicle() function returning a Vehicle object.

 Banking: create_account(customer_name) returning a BankAccount.

🛠️How to Apply?

def create_customer(name, age):


class Customer:
def __init__(self, name, age):
self.name = name
self.age = age
return Customer(name, age)

c1 = create_customer("Ravi", 35)
print(c1.name, c1.age)

5. Objects are Mutable


✅ What it is?
 Objects' attributes can be changed after creation.
 The object reference remains the same, but its state can be modified.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


📍When and Where to Apply?
 To update object data dynamically:
 Automotive: Update a car’s fuel level as it drives.
 Banking: Update a customer’s balance after transactions.

🛠️How to Apply?

class BankAccount:
def __init__(self, balance):
self.balance = balance

acc = BankAccount(1000)
acc.balance += 500 # Deposit
print(acc.balance) # Output: 1500

6. Copying Objects
✅ What it is?
 Copying can be shallow (new reference) or deep (new object with copied values)

📍When and Where to Apply?


 Needed when duplicating an object without affecting the original.
 Automotive: Clone vehicle configuration templates.
 Banking: Duplicate account for analysis without affecting the real one.

🛠️How to Apply?

import copy

class Car:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed

car1 = Car("Volvo", 100)


car2 = copy.copy(car1) # Shallow copy
car3 = copy.deepcopy(car1) # Deep copy

🔄 Summary Table
Concept Use Case - Automotive Use Case - Banking
Class/Object Vehicle, Engine, Sensor Customer, Account, Transaction
Attributes speed, fuel_type, engine_on balance, IFSC, account_type
Rectangle Parking area, sensor zone ATM screen, branch layout
Instances as Return create_engine(), build_car() open_account(), new_customer()

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


Concept Use Case - Automotive Use Case - Banking
Mutable Objects update speed, temperature deposit, withdraw, update KYC
Object Copying clone vehicle config replicate account for audit

1. Time Class
✅ What it is?
 A class used to represent time as an object with attributes like hour, minute, and
second.

 Helps in organizing and manipulating time-related data using object-oriented design.

📍When and Where to Apply?


Domain Use Cases
Automotive Trip duration, engine run time, fuel usage logs
Banking Transaction timestamps, session durations, interest calculation timeframes

🛠️How to Apply?

class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second

def print_time(self):
print(f"{self.hour:02d}:{self.minute:02d}:{self.second:02d}")

t1 = Time(10, 45, 30)


t1.print_time() # Output: 10:45:30

🔷 2. Pure Functions
✅ What it is?
 Functions that do not modify objects passed to them.
 They take objects as input, perform computations, and return new objects without altering
the original.

📍When and Where to Apply?


Domain Use Cases
Automotive Calculating estimated arrival time without changing current time object
Banking Calculating interest or maturity date without modifying the original account object

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


🛠️How to Apply?

def add_time(t1, t2):


total_seconds = (t1.hour + t2.hour) * 3600 + (t1.minute + t2.minute) * 60 +
(t1.second + t2.second)
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
return Time(hours, minutes, seconds)

start = Time(1, 20, 30)


duration = Time(2, 45, 15)
end = add_time(start, duration)
end.print_time() # Output: 04:05:45

Note: add_time() does not change start or duration.

🔷 3. Modifiers (Mutators)
✅ What it is?
 Functions that modify the object passed to them, typically through self.

 Called mutator methods or modifiers because they change internal state.

📍When and Where to Apply?


Domain Use Cases
Automotive Updating trip time as the car moves
Banking Adjusting account balance, updating interest period

🛠️How to Apply?

def increment(time_obj, seconds):


time_obj.second += seconds
while time_obj.second >= 60:
time_obj.second -= 60
time_obj.minute += 1
while time_obj.minute >= 60:
time_obj.minute -= 60
time_obj.hour += 1

trip_time = Time(2, 50, 30)


increment(trip_time, 500) # Mutates original object
trip_time.print_time() # Output will reflect updated time

🧠 Summary Table
Concept Description Automotive Example Banking Example
Represents hours,
Time Class Drive duration, sensor logs Session time, transaction logs
minutes, seconds

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


Concept Description Automotive Example Banking Example
Pure Returns new object, no Estimated arrival time Interest computation, EMI
Function side-effects calculation scheduler
Alters the existing object Increment trip time, update Update account after deposit/
Modifier
directly engine timer withdrawal

🧪 Simple Practice Examples


Banking: Add transaction time to current time (Pure Function)

def add_transaction_time(current_time, txn_duration):


return add_time(current_time, txn_duration)

Automotive: Update engine run-time (Modifier)

def update_engine_time(engine_time, seconds):


increment(engine_time, seconds)

1. Object-Oriented Features
✅ What it is?
OOP is a programming paradigm based on objects. Python supports:
 Encapsulation: Bundling data and methods.
 Abstraction: Hiding implementation details.
 Inheritance: Reusing code via parent-child relationships.
 Polymorphism: Different classes respond to same method.

📍When/Where to Apply?
 Automotive: Design Vehicle, Car, Truck classes.

 Banking: Use Account, SavingsAccount, LoanAccount.

🛠️How to Apply?

class Vehicle:
def start(self):
print("Vehicle starting...")

class Car(Vehicle):
def start(self):
print("Car starting with key...")

v = Vehicle()
c = Car()
v.start() # Vehicle starting...
c.start() # Car starting with key...

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


🔷 2. Printing Objects
✅ What it is?
 When printing an object, Python uses the special method __str__() or __repr__().

📍Where to Apply?
 For debugging/logging object state.

🛠️How to Apply?

class Customer:
def __init__(self, name, balance):
self.name = name
self.balance = balance

def __str__(self):
return f"Customer: {self.name}, Balance: ₹{self.balance}"

cust = Customer("Anita", 5000)


print(cust)

🔷 3. Another Example: Transaction Class


class Transaction:
def __init__(self, amount, type):
self.amount = amount
self.type = type

def __str__(self):
return f"{self.type} of ₹{self.amount}"

t = Transaction(1000, "Deposit")
print(t)

🏦 Can be extended for ATM, Online Transfer, etc.

🔷 4. A More Complicated Example


✅ Description:
Combining multiple classes and methods to represent a real-world object.

🛠️Automotive Example:

class Engine:
def __init__(self, power):
self.power = power

def __str__(self):
return f"{self.power} HP Engine"

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


class Car:
def __init__(self, brand, engine):
self.brand = brand
self.engine = engine

def __str__(self):
return f"{self.brand} with {self.engine}"

e = Engine(150)
c = Car("Volvo", e)
print(c) # Volvo with 150 HP Engine

🔷 5. The __init__() Method


✅ What it is?
 The constructor of the class.
 Automatically invoked during object creation.

📍When to Use?
 When initializing object attributes.

class Account:
def __init__(self, acc_no, balance):
self.acc_no = acc_no
self.balance = balance

🔷 6. The __str__() Method


✅ What it is?
 A string representation of the object.
 Used by print() and str().
python
CopyEdit
class Sensor:
def __init__(self, id, value):
self.id = id
self.value = value

def __str__(self):
return f"Sensor ID: {self.id}, Value: {self.value}"

s = Sensor("TMP101", 36.6)
print(s)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


🔷 7. Operator Overloading
✅ What it is?
 You can redefine standard operators like +, ==, etc., for custom behavior.

🛠️Banking Example:

class Money:
def __init__(self, amount):
self.amount = amount

def __add__(self, other):


return Money(self.amount + other.amount)

def __str__(self):
return f"₹{self.amount}"

m1 = Money(1000)
m2 = Money(500)
m3 = m1 + m2
print(m3) # ₹1500

🔷 8. Type-Based Dispatch
✅ What it is?
 Different logic based on argument type.

📍Example:

def display(info):
if isinstance(info, str):
print("Name:", info)
elif isinstance(info, int):
print("Account Number:", info)

display("Vishwa")
display(123456)

🔷 9. Polymorphism
✅ What it is?
 Different classes implement the same method in different ways.

📍Where to Use?
 Banking: Different accounts have calculate_interest().

 Automotive: Different vehicles implement start() differently.

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


class LoanAccount:
def calculate_interest(self):
return "Interest at 10%"

class SavingsAccount:
def calculate_interest(self):
return "Interest at 4%"

for acc in [LoanAccount(), SavingsAccount()]:


print(acc.calculate_interest())

🔷 10. Interface and Implementation


✅ What it is?
 Interface: What a class exposes (e.g., methods).
 Implementation: How those methods work internally.

📍Why Use It?


 To separate what an object does from how it does it.
 Enables flexibility and modular design.

🛠️Example:

class Vehicle:
def start(self): # Interface
raise NotImplementedError

class Car(Vehicle):
def start(self): # Implementation
print("Car starts with a push button.")

class Truck(Vehicle):
def start(self):
print("Truck starts with ignition key.")

🧠 Summary Table
Concept Description Automotive Use Banking Use
Account(acc_no,
__init__() Initializes object Engine(power)
balance)
Customer,
__str__() String representation Sensor, Car
Transaction
Operator Distance +
Redefining +, ==, etc. Money + Money
Overloading Distance
Behavior based on log_data(sensor) display(info)
Type Dispatch
argument type
Polymorphism Shared interface, start() in Car, calculate_interest()

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M


Concept Description Automotive Use Banking Use
different behavior Truck
Account.compute_tax(
Interface & Impl. Abstraction Vehicle.start()
)

Notes Prepared by: Dr. Vishwa Kiran S, Dept of CSBS, BMSIT&M

You might also like