← Programming Concepts in Mechanical Engineering (25ME34I)
Object-Oriented Programming
Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III
Read with diagrams, search and self-test
After studying this chapter you will be able to:
• Explain classes, objects, attributes and methods.
• Write classes with the __init__ constructor and the self parameter.
• Distinguish class attributes and instance attributes.
• Implement inheritance and method overriding, and use super().
• Explain and demonstrate encapsulation, abstraction and polymorphism.
7.1 Procedural vs Object-Oriented Programming
In procedural programming, a program is a sequence of functions acting on data stored separately. As programs grow, it becomes hard to keep track of which function changes which data. Object-Oriented Programming (OOP) bundles data and the functions that work on it into a single unit called an object. It models the real world: a machine shop has lathes, motors and robots, each with its own data (properties) and behaviour (operations).
| Procedural programming | Object-oriented programming |
|---|---|
| Program divided into functions | Program divided into objects |
| Data and functions are separate | Data and methods are bundled together |
| Top-down approach | Bottom-up approach |
| Data can be accessed freely (less secure) | Data hiding through encapsulation |
| Code reuse through functions | Code reuse through inheritance |
| Examples: C, Fortran | Examples: Python, Java, C++ |
7.2 Classes and Objects
A class is a blueprint or template that defines the attributes (data) and methods (functions) common to all objects of one kind. An object (or instance) is a real entity created from the class with its own values. The drawing of a bolt is the class; each bolt manufactured from it is an object.
Fig. 7.1 A class is a blueprint; objects are instances
• Attributes: variables that hold the state of an object (model, year, colour).
• Methods: functions defined inside a class that describe behaviour (start, stop).
• Constructor `__init__`: a special method called automatically when an object is created; it initialises the attributes.
• self: the first parameter of every instance method; it refers to the object on which the method is called.
class ClassName:
class_attribute = value
def __init__(self, p1, p2):
self.attr1 = p1 # instance attributes
self.attr2 = p2
def method(self):
statements
obj = ClassName(v1, v2) # create object
obj.method() # call methodclass Motor:
def __init__(self, power_kw, rpm):
self.power_kw = power_kw
self.rpm = rpmdef torque(self):
return 9550 * self.power_kw / self.rpm # N.mm1 = Motor(7.5, 1440)
m2 = Motor(15, 960)
print(f"Motor 1 torque = {m1.torque():.2f} N.m")
print(f"Motor 2 torque = {m2.torque():.2f} N.m")
print("m1 rpm attribute:", m1.rpm)Motor 1 torque = 49.74 N.m Motor 2 torque = 149.22 N.m m1 rpm attribute: 1440
The constant 9550 comes from T = 60000 P / (2πN) ≈ 9549 P/N for P in kW and T in N·m.
Class attributes vs instance attributes
class Bolt:
material = "Steel 8.8" # class attribute (shared)
count = 0
def __init__(self, size, length):
self.size = size # instance attributes
self.length = length
Bolt.count += 1b1 = Bolt("M10", 50); b2 = Bolt("M12", 60)
print(b1.size, b2.size, b1.material, b2.material)
print("Bolts created:", Bolt.count)M10 M12 Steel 8.8 Steel 8.8 Bolts created: 2
| Class attribute | Instance attribute |
|---|---|
| Defined in the class body | Defined inside __init__ using self |
| Shared by all objects | Separate copy for each object |
| Accessed as ClassName.attr | Accessed as obj.attr |
| Example: material, count | Example: size, length |
7.3 Inheritance
Inheritance allows a new class (child / derived / sub class) to acquire the attributes and methods of an existing class (parent / base / super class). The child can add new features and modify inherited ones. It promotes code reuse and represents the "IS-A" relationship: a Dog IS-A Animal, a CNC lathe IS-A machine tool.
Syntax: class Child(Parent):
Fig. 7.2 Inheritance: Dog and Cat derived from Animal
Types of inheritance
| Type | Structure | Example |
|---|---|---|
| Single | One parent → one child | Machine → Lathe |
| Multilevel | Grandparent → parent → child | Machine → Lathe → CNCLathe |
| Hierarchical | One parent → many children | Animal → Dog, Cat |
| Multiple | Many parents → one child | Motor, Pump → MotorPump |
| Hybrid | Combination | – |
super()
super() calls a method of the parent class, typically the parent's __init__, so that the child does not have to repeat the initialisation code.
class Machine:
def __init__(self, name, power):
self.name = name
self.power = power
def info(self):
return f"{self.name}: {self.power} kW"class Lathe(Machine): # single inheritance
def __init__(self, name, power, swing):
super().__init__(name, power) # reuse parent init
self.swing = swing
def info(self): # overriding
return super().info() + f", swing {self.swing} mm"class CNCLathe(Lathe): # multilevel
def __init__(self, name, power, swing, controller):
super().__init__(name, power, swing)
self.controller = controller
def info(self):
return super().info() + f", {self.controller}"for m in (Machine("Drill", 1.5), Lathe("HMT NH22", 5.5, 430),
CNCLathe("Jobber XL", 7.5, 400, "Fanuc 0i")):
print(m.info())
print(isinstance(CNCLathe("x", 1, 1, "y"), Machine))Drill: 1.5 kW HMT NH22: 5.5 kW, swing 430 mm Jobber XL: 7.5 kW, swing 400 mm, Fanuc 0i True
7.4 Method Overriding
When a child class defines a method with the same name and parameters as a method in the parent class, the child's version overrides (replaces) the parent's version for objects of the child class. The parent method can still be called with super(). Overriding is the basis of run-time polymorphism.
7.5 Encapsulation
Encapsulation is wrapping data and methods into one unit (class) and restricting direct access to some data. Python uses naming conventions:
• self.name – public: accessible everywhere.
• self._name – protected (convention): meant for internal and subclass use.
• self.__name – private: name-mangled, not directly accessible from outside.
Access to private data is given through methods (getters/setters) or the @property decorator, which can validate values.
class Tank:
def __init__(self, capacity):
self.capacity = capacity
self.__level = 0 # private attributedef fill(self, litres):
if litres < 0:
print("Invalid quantity"); return
self.__level = min(self.capacity, self.__level + litres)
@property
def level(self): # read-only access
return self.__levelt = Tank(500)
t.fill(350); t.fill(300); t.fill(-5)
print("Level =", t.level, "litres")
try:
print(t.__level)
except AttributeError as e:
print("Direct access blocked:", e)Invalid quantity Level = 500 litres Direct access blocked: 'Tank' object has no attribute '__level'
7.6 Abstraction
Abstraction means showing only the essential features and hiding the implementation details. A driver uses the accelerator without knowing the fuel-injection logic. In Python, abstraction is achieved with abstract base classes (module abc): an abstract method declares *what* must be done; each subclass decides *how*. An abstract class cannot be instantiated.
from abc import ABC, abstractmethod import math
class Section(ABC):
@abstractmethod
def area(self):
passclass Circle(Section):
def __init__(self, d): self.d = d
def area(self): return math.pi * self.d ** 2 / 4class Rectangle(Section):
def __init__(self, b, h): self.b, self.h = b, h
def area(self): return self.b * self.hfor s in (Circle(20), Rectangle(30, 10)):
print(type(s).__name__, "area =", round(s.area(), 2), "mm^2")
try:
Section()
except TypeError:
print("Error: abstract class Section cannot be instantiated")Circle area = 314.16 mm^2 Rectangle area = 300 mm^2 Error: abstract class Section cannot be instantiated
7.7 Polymorphism
Polymorphism ("many forms") means that the same method name or operator behaves differently depending on the object. Examples:
• Operator polymorphism: + adds numbers, joins strings and concatenates lists.
• Method overriding: speak() gives "Woof" for Dog and "Meow" for Cat.
• Duck typing: any object having an area() method can be used in the same loop, as in the Section example above.
• Operator overloading: defining __add__, __str__ etc. in a class.
print(2 + 3, "Gear" + "box", [1] + [2])
class Force:
def __init__(self, fx, fy): self.fx, self.fy = fx, fy
def __add__(self, other): # overload +
return Force(self.fx + other.fx, self.fy + other.fy)
def __str__(self):
return f"Force({self.fx} N, {self.fy} N)"R = Force(300, 400) + Force(-100, 50)
print("Resultant:", R)5 Gearbox [1, 2] Resultant: Force(200 N, 450 N)
Fig. 7.3 The four pillars of OOP
7.8 Practice Programs (Week 7)
Program 7.1 – Class Car with start, stop and display methods
# Program 7.1: Car class
class Car:
wheels = 4 # class attributedef __init__(self, model, year, color):
self.model = model
self.year = year
self.color = color
self.running = Falsedef start(self):
if self.running:
print(self.model, "is already running")
else:
self.running = True
print(self.model, "engine started")def stop(self):
if self.running:
self.running = False
print(self.model, "engine stopped")
else:
print(self.model, "is already stopped") def display(self):
state = "Running" if self.running else "Stopped"
print(f"Model: {self.model} | Year: {self.year} | "
f"Color: {self.color} | Wheels: {Car.wheels} | {state}")
car1 = Car("Tata Nexon", 2023, "Blue")
car2 = Car("Maruti Swift", 2021, "Red")
car1.display()
car1.start(); car1.start()
car1.display()
car1.stop()
car2.display(); car2.stop()Model: Tata Nexon | Year: 2023 | Color: Blue | Wheels: 4 | Stopped Tata Nexon engine started Tata Nexon is already running Model: Tata Nexon | Year: 2023 | Color: Blue | Wheels: 4 | Running Tata Nexon engine stopped Model: Maruti Swift | Year: 2021 | Color: Red | Wheels: 4 | Stopped Maruti Swift is already stopped
Program 7.2 – Inheritance: Animal, Dog and Cat
# Program 7.2: Hierarchical inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "makes a sound"
def info(self):
print(f"{self.name} ({type(self).__name__}) {self.speak()}")class Dog(Animal):
def speak(self):
return "says Woof!"
def fetch(self):
print(self.name, "fetches the ball")class Cat(Animal):
def speak(self):
return "says Meow!"for a in [Animal("Generic"), Dog("Tommy"), Cat("Kitty")]:
a.info()
Dog("Tommy").fetch()
print(issubclass(Dog, Animal), isinstance(Cat("k"), Animal))Generic (Animal) makes a sound Tommy (Dog) says Woof! Kitty (Cat) says Meow! Tommy fetches the ball True True
The method info() is written only once in Animal but works for Dog and Cat (inheritance). Each subclass gives its own speak() (method overriding / polymorphism).
Program 7.3 – Demonstrating method overriding
# Program 7.3: Method overriding with super()
class Shape:
def area(self):
return 0
def describe(self):
print(f"{type(self).__name__}: area = {self.area():.2f}")class Square(Shape):
def __init__(self, a): self.a = a
def area(self): # overrides Shape.area
return self.a ** 2class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): # overrides Shape.area
return 3.14159 * self.r ** 2class Ring(Circle):
def __init__(self, R, r):
super().__init__(R); self.ri = r
def area(self): # extends parent's version
return super().area() - 3.14159 * self.ri ** 2for s in (Shape(), Square(4), Circle(3), Ring(5, 3)):
s.describe()Shape: area = 0.00 Square: area = 16.00 Circle: area = 28.27 Ring: area = 50.27
Program 7.4 – Bank account: deposit, withdraw and balance
# Program 7.4: Bank account class with encapsulation
class BankAccount:
def __init__(self, holder, acc_no, balance=0.0):
self.holder = holder
self.acc_no = acc_no
self.__balance = balance # privatedef deposit(self, amount):
if amount <= 0:
print("Deposit amount must be positive")
else:
self.__balance += amount
print(f"Deposited Rs {amount:.2f}")def withdraw(self, amount):
if amount <= 0:
print("Withdrawal amount must be positive")
elif amount > self.__balance:
print("Insufficient balance!")
else:
self.__balance -= amount
print(f"Withdrawn Rs {amount:.2f}")def get_balance(self):
return self.__balancedef show(self):
print(f"A/c {self.acc_no} ({self.holder}) "
f"balance: Rs {self.__balance:.2f}")acc = BankAccount("Ravi Kumar", "SB1024", 5000)
acc.show()
acc.deposit(2500)
acc.withdraw(10000)
acc.withdraw(3000)
acc.deposit(-50)
print("Balance enquiry: Rs", acc.get_balance())A/c SB1024 (Ravi Kumar) balance: Rs 5000.00 Deposited Rs 2500.00 Insufficient balance! Withdrawn Rs 3000.00 Deposit amount must be positive Balance enquiry: Rs 4500
Program 7.5 – Engineering class: a shaft object
import math
class Shaft:
def __init__(self, d, L, G=80000):
self.d, self.L, self.G = d, L, G # mm, mm, MPa
def polar_moment(self):
return math.pi * self.d ** 4 / 32
def shear_stress(self, T): # T in N.mm
return 16 * T / (math.pi * self.d ** 3)
def twist_deg(self, T):
J = self.polar_moment()
return math.degrees(T * self.L / (self.G * J))s = Shaft(40, 1000)
T = 500e3 # 500 N.m
print(f"J = {s.polar_moment():.0f} mm^4")
print(f"Max shear stress = {s.shear_stress(T):.2f} MPa")
print(f"Angle of twist = {s.twist_deg(T):.3f} deg")J = 251327 mm^4 Max shear stress = 39.79 MPa Angle of twist = 1.425 deg
7.9 Solved Exam Questions
Q1. Explain class and object with an example. (6 marks)
Answer: A class is a user-defined blueprint containing attributes and methods; an object is an instance of a class with actual values. Example: class Motor with attributes power and rpm and method torque(); m1 = Motor(7.5, 1440) creates an object. Many objects can be created from one class, each with its own data.
Q2. What is the purpose of the __init__ method and the self parameter? (5 marks)
Answer: __init__ is the constructor, called automatically when an object is created; it initialises instance attributes from the arguments. self refers to the current object; through it methods access and modify that object's attributes (self.rpm). Python passes the object automatically: m1.torque() is executed as Motor.torque(m1).
Q3. Define inheritance. Explain its types with a program. (7 marks)
Answer: Inheritance lets a child class acquire the attributes and methods of a parent class, enabling reuse and extension. Types: single, multilevel, hierarchical, multiple and hybrid (table in Section 7.3). Programs: Machine → Lathe → CNCLathe (multilevel) and Animal → Dog, Cat (hierarchical, Program 7.2).
Q4. What is method overriding? Write a program to demonstrate it. (6 marks)
Answer: Redefining a parent-class method in a child class with the same name so that the child's version is used for child objects. See Program 7.3.
Q5. Explain encapsulation, abstraction and polymorphism. (8 marks)
Answer: Encapsulation – bundling data with methods and restricting access (private __balance in BankAccount, accessed only through deposit/withdraw). Abstraction – exposing only essential features, hiding details; abstract base class Section with abstract method area(). Polymorphism – one interface, many forms; area() behaves differently for Circle and Rectangle, + works for numbers, strings and Force objects.
7.10 Multiple Choice Questions
1. A class is a a) built-in function b) blueprint for creating objects c) module d) loop
Answer: (b) Reason: A class defines the structure and behaviour; objects are created from it.
2. The constructor method in Python is a) __start__ b) __init__ c) constructor() d) __new_object__
Answer: (b) Reason: __init__ runs automatically when an object is created.
3. self refers to a) the class b) the current object c) the parent class d) a global variable
Answer: (b) Reason: self is the instance on which the method is called.
4. Acquiring properties of one class in another is a) encapsulation b) inheritance c) abstraction d) polymorphism
Answer: (b) Reason: The child class inherits attributes and methods of the parent.
5. class B(A): means a) A inherits B b) B inherits A c) A and B are unrelated d) B is abstract
Answer: (b) Reason: The parent class is written in brackets after the child's name.
6. A private attribute in Python is written as a) _name b) __name c) private name d) name_
Answer: (b) Reason: Two leading underscores trigger name mangling, preventing direct outside access.
7. Same method name behaving differently in different classes is a) encapsulation b) polymorphism c) inheritance d) abstraction
Answer: (b) Reason: Polymorphism means many forms of one interface.
8. Which function calls the parent class method? a) parent() b) super() c) base() d) self()
Answer: (b) Reason: super() returns a proxy to the parent class.
9. An abstract class a) can be instantiated b) cannot be instantiated c) has no methods d) is always private
Answer: (b) Reason: Classes with unimplemented abstract methods raise TypeError on instantiation.
10. Machine → Lathe → CNCLathe is an example of a) multiple inheritance b) multilevel inheritance c) hierarchical inheritance d) hybrid inheritance
Answer: (b) Reason: Each class inherits from the one above it in a chain.
11. Animal → Dog and Animal → Cat is a) single b) multilevel c) hierarchical d) multiple
Answer: (c) Reason: One parent with several children is hierarchical inheritance.
12. A variable shared by all objects of a class is a a) local variable b) instance attribute c) class attribute d) private attribute
Answer: (c) Reason: Class attributes are defined in the class body and shared.
13. Which module provides abstract base classes? a) abstract b) abc c) oop d) base
Answer: (b) Reason: from abc import ABC, abstractmethod.
14. Defining __add__ in a class allows a) inheritance b) operator overloading of + c) encapsulation d) file handling
Answer: (b) Reason: Python calls __add__ when + is used on objects of that class.
15. isinstance(obj, Cls) returns a) the class of obj b) True if obj is an instance of Cls or its subclass c) a new object d) None
Answer: (b) Reason: It checks the IS-A relationship including inheritance.
7.11 Exercises
1. Create a class Gear with teeth and module; add methods for pitch-circle diameter and circular pitch.
2. Create a class Employee and derive Operator and Supervisor with different salary calculations.
3. Create a class Beam with a method for maximum bending moment of a simply supported beam with central load; derive CantileverBeam and override the method.
4. Create a Student class with private marks and a method to compute grade.
5. Write an abstract class Machine with abstract method efficiency() and implement it for Pump and Turbine.