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

Object Oriented Programming in Python

Inheritance is a key concept in Object-Oriented Programming where a child class inherits properties and behaviors from a parent class, allowing for code reuse and reducing redundancy. It can be categorized into single, multilevel, and multiple inheritance, each serving different structural needs in programming. Understanding inheritance helps in creating realistic models that mirror real-world hierarchies, while also simplifying code maintenance and development.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

Object Oriented Programming in Python

Inheritance is a key concept in Object-Oriented Programming where a child class inherits properties and behaviors from a parent class, allowing for code reuse and reducing redundancy. It can be categorized into single, multilevel, and multiple inheritance, each serving different structural needs in programming. Understanding inheritance helps in creating realistic models that mirror real-world hierarchies, while also simplifying code maintenance and development.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is Inheritance.

Inheritance is a fundamental Object-Oriented Programming (OOP) concept


where:

A child class acquires the properties (data) and behaviors (functions) of a


parent class.

In very simple words:

 One class is already built

 Another class reuses it instead of starting from zero

Mechanical Engineering Analogy

Think of standard machine design:

 All machines have:

o Brand

o Power

o Start/Stop behavior

But:

 A CNC Machine has extra features

 A Welding Machine has different features

Instead of redesigning everything:

 You create a general machine

 Then specialize in it

That is inheritance.

Why Inheritance is Important for Engineering Students

Without Inheritance

 Repeated code

 More errors
 Difficult to modify systems

 Unrealistic system design

With Inheritance

 Code is written once

 Used by many machine types

 Changes affect all machines

 Mirrors real physical hierarchies

Aspect Benefit
Development time Reduced
Code length Shorter
Maintenance Easier
System realism High

Parent (Base)

What is a Parent Class?

A parent class:

 Defines general behavior

 Representing a common concept

 Is not very specific


Child (Derived) Class

What is a Child Class?

A child class:

 Inherits everything from the parent

 Adds extra features

 Can modify parent behavior

Example

This means:

CNC_Mill IS A Machine

This is the “Is-A relationship”.

A new function, specific only to CNC machines.

Is-A Relationship (Very Important Concept)

Inheritance should follow Is-A logic.

Valid Examples

 CNC_Mill is a Machine

 WeldingMachine is a Machine

 Robot is a Machine

Invalid Examples

 ToolBox is a Machine
 Engineer is a Machine

If “IS-A” makes sense → use inheritance.

How Inherited Methods Work

Assume this class structure:

Step 1: Object Creation


Step 2: Method Call Begins

Step 3: Method Lookup – The Core Mechanism

Python follows a fixed internal order called


Method Resolution Order (MRO)

For single inheritance, the order is:

1. CNC_Mill (child class)

2. Machine (parent class)

3. object (Python’s built-in base class)

Step 4: Python Searches in Child Class First

Python first checks:

Question:

Does CNC_Mill have a start() method?

No.

So Python does NOT fail.


Instead, it automatically moves up to the parent.

Step 5: Python Moves to Parent Class


Python now checks:

Yes, start() exists here.

So Python:

 Takes this method

 Binds it to the object my_mill

 Executes it

This is automatic inheritance in action.

Step 6: Why self Still Works

Even though start() is written in Machine,


self still refers to my_mill.

Important Understanding:

 self always refers to the object that called the method

 Not the class where method is written

So internally:

Step : Why Python Doesn’t Copy Code

Python does not copy parent methods into the child class.

Instead:

 Child class keeps a reference to the parent

 Uses parent methods only when needed


Mechanical Engineering Analogy

Imagine:

 CNC_Mill is a special machine

 It doesn’t have its own start procedure

 So it uses the standard machine start procedure

Engineer asks:

“How does this CNC start?”

Answer:

“Follow the standard machine startup.”

That’s exactly what Python does.

Step 9 : What If Child Has Its Own start ()?

Now Python’s search stops at step 1.

New Flow:

1. CNC_Mill → start() ✔

2. Parent is not checked


3. Parent method is ignored

This is method overriding.

Step 9: Internal Flow Summary

When my_mill.start() is executed:

1. Python identifies the object’s class

2. Searches method in child class

3. If not found, searches parent class

4. Executes the first match

5. Passes object as self

super() – Method

What is super()?

super() is used to:

 Access parent class methods

 Especially parent constructor

Why Needed?

Without super():

 Parent variables won’t exist

 Object becomes incomplete

What super() does:

 Calls Machine.__init__()

 Initializes brand & power

 Then adds CNC-specific data


Method Overriding (Engineering Context)

What is Method Overriding?

When a child changes parent behavior.

Example

Now:

 Parent start() is replaced

 CNC behaves differently

Engineering Meaning

Different machines:

 Start differently

 Have different safety checks

What is Multilevel Inheritance?

Multilevel inheritance means:

A class inherits from another class, and then another class inherits from that
child’s class.

In simple words:

 Parent → Child → Grandchild

Why is Multilevel Inheritance Needed?

In engineering systems:

 Machines are classified in levels

 Each level adds more specialization

Example hierarchy:
 Machine

 CNC Machine

 Robotic CNC Machine

This is exactly multilevel inheritance.

Mechanical Engineering

Think of machine evolution:

 A Machine has basic properties

 A CNC Machine is a special machine

 A Robotic CNC Machine is a more advanced CNC

Each level:

 Uses previous features

 Adds something new

Multilevel Inheritance Syntax

Simple example of multi-level Inheritance Syntax:


Object Creation:

Internal Working (VERY IMPORTANT)

One-Line Explanation of (Multilevel)

Multilevel inheritance allows a class to inherit from a child class,


forming a chain of inheritance.
Main Problems of Multilevel Inheritance

Problem 1: Increased Complexity

As inheritance levels increase:

Machine → CNC → Robotic CNC → AI CNC → Smart CNC

 Code becomes harder to understand

 Students / developers lose track of where methods come from

Engineering analogy:
Too many gear stages → harder maintenance.

Problem 3: Tight Coupling

Lower classes depend heavily on upper classes.

If you change the base class:

 All child classes are affected

Engineering analogy:
Changing shaft diameter affects all connected gears.

When Multilevel Inheritance is GOOD

Multilevel inheritance is good and safe when:

✔ Clear hierarchy exists


✔ Each level adds small, logical features
✔ Depth is limited (2–3 levels)
✔ “IS-A” relationship is very clear

Multilevel inheritance may increase complexity and maintenance


difficulty if the inheritance chain becomes too deep.

Scenario: Industrial Fluid Handling System

In a chemical processing plant, different machines are used to move fluids.


These machines are naturally classified in levels.

Real Physical Hierarchy

 Machine → any industrial machine

 RotatingMachine → machines with rotating shafts

 CentrifugalPump → a specific type of rotating machine


This is a perfect case for multilevel inheritance.
(One Line)

“We use multilevel inheritance here because a pump is naturally a


rotating machine, and a rotating machine is naturally a machine.”

Multiple Inheritance (Mechanical + Control Systems View)

What is Multiple Inheritance?

Multiple inheritance is an Object-Oriented Programming concept where one


child class inherits features (variables and methods) from more than one
parent class.

In simple words:

One class = combination of multiple parent classes

Simple idea

 A machine is mechanical

 The same machine is also electrical

 Instead of rewriting code, we inherit both features

This is very common in real engineering systems.

Why do we need Multiple Inheritance?

Without Multiple Inheritance

 Code duplication increases

 Same logic written again and again

 Hard to maintain

 Poor modeling of real systems

With Multiple Inheritance

 Reuse existing classes

 Combine different systems cleanly

 Real-world modeling becomes accurate

 Cleaner and professional design


Engineering Perspective

In mechanical engineering:

 A robot is:

o A mechanical structure

o An electrical system

o A control system

Multiple inheritance allows:

One object to represent multiple engineering domains.

Key Rule

 Python searches for parents from left to right

 This order matters (important later in Method Resolution Order – MRO)

Small & Simple Example


What happened internally?
How Multiple Inheritance Works Internally (Python Logic)

Python uses Method Resolution Order (MRO).

When a method is called:

1. Python checks child class

2. Then first parent

3. Then second parent

4. Then base object class

This prevents confusion and ensures predictable behavior.

Real-World Mechanical Engineering Scenario

Scenario: Smart Hydraulic Press

A Smart Hydraulic Press has:

 Hydraulic force system

 Electrical power & sensors

Both systems are independent but operate together.


Constructor initialization in Multiple inheritance:
Each parent class has its own __init__ constructor

 MechanicalSystem. __init__ sets self.fan_speed

 Electrical System. __init__ sets self. Voltage and self. Power

By calling them explicitly, we ensure that both sets of attributes are


initialized properly inside the child object (Sarthak).

Why not use super()?

 In single inheritance, super() works perfectly:

 But in multiple inheritance, super() follows Python’s Method


Resolution Order (MRO).

For SmartHVAC(MechanicalSystem, ElectricalSystem):

 Python will only call the first parent in the MRO, which is
MechanicalSystem

 ElectricalSystem.__init__ won’t run automatically unless:

o It also calls super()

o And every parent in the chain cooperates

For beginners, this is complex and confusing, and might leave some
attributes uninitialized.

Explicit calls = safe and clear


 Guarantees both parent constructors run

 All attributes (fan_speed, voltage, power) exist in the child object

 Easy to visualize and teach for students

Analogy: You are assembling a real HVAC unit:

1. Install the mechanical fan system

2. Install the electrical control system


You cannot skip either, otherwise the machine won’t function properly.

We call MechanicalSystem.__init__ and ElectricalSystem.__init__ explicitly because


Python won’t automatically initialize both parent constructors in multiple inheritance, and we
want all parts of the child object fully set up.

When Multiple Inheritance is GOOD

✔ Machine combines independent systems


✔ Parents have distinct responsibilities
✔ Clear real-world mapping
✔ Minimal method name conflicts

When NOT to Use It

When classes are tightly dependent


When deep confusion arises
When composition is a better fit

(We already discussed why composition can sometimes be better.)

Final One-Line

Multiple inheritance is used when a system must combine multiple


independent features into one working unit.
1. What is Diamond Problem?

The Diamond Problem happens in multiple inheritance when:

One base class is inherited by two classes

And those two classes are inherited by one final class

So the same base class appears twice in the hierarchy

Problem:

Which path should Python follow to reach class A?


And should A run once or multiple times?

Scenario (Mechanical System – Problem Case)

Real-life idea:

A workshop system:

 Machine → basic machine behavior

 MechanicalSystem → mechanical features

 ElectricalSystem → electrical features

 SmartMachine → combination of both

Problem Code (Without Proper Handling)


What’s the Issue?

[Link]() is called TWICE

Because:

 Mechanical → calls Machine

 Electrical → calls Machine again

This is the Diamond Problem.

. Solution (Using super() + MRO)

Python solves this using:

 super()

 MRO (Method Resolution Order)


4. Why This Works?

Python follows MRO order

SmartMachine → MechanicalSystem → ElectricalSystem → Machine

So:

 Each class calls super()


 Python moves forward in order
 Machine runs only once

Scenario: Smart Machine Startup System

A startup company is developing smart industrial machines for automated factories. Each
machine consists of a mechanical system (gears, motors) and an electrical system (power supply,
wiring). Both of these systems depend on a common base system that handles the basic machine
startup process.

While testing, the engineers noticed a problem:

 When the smart machine starts, both the mechanical and electrical systems try to execute
the base startup process separately.
 As a result, the machine startup process runs multiple times, causing duplication and
inefficient operation.

The company now wants to design a solution using object-oriented programming so that:

 Each system performs its own startup steps


 The base machine startup process is executed only once
 The system follows a proper sequence without duplication

You might also like