Unit 3
Unit 3
Object Oriented
Concept
Features of Object Oriented
Programming
• Inheritance:
– Inheritance allows us to define a class that inherits
all the methods and properties from another class.
– Parent class is the class being inherited from, also
called base class.
– Child class is the class that inherits from another
class, also called derived class.
Example: A class Dog might inherit from a general
Animal class, taking on its properties like name and
age, as well as methods like eat() and sleep().
Features of Object Oriented Programming
• Polymorphism:
– The word polymorphism means having many forms.
In programming, polymorphism means the same
function name (but different signatures) being used
for different types. The key difference is the data types
and number of arguments used in function.
• Example: A function may behave differently based
on the input, or different classes might have
methods with the same name that perform
different tasks.
• Abstraction:
– Abstraction involves hiding the complex
implementation details and showing only the essential
features of the object. It simplifies the complexity by
allowing the user to interact with the objects at a
higher level.
– A simple example of this can be a car. A car has an
accelerator, clutch, and break and we all know that
pressing an accelerator will increase the speed of
the car and applying the brake can stop the car but
we don’t know the internal mechanism of the car
and how these functionalities can work this detail
hiding is known as data abstraction.
Features of Object Oriented
Programming
• Modularity
• Definition: Modularity refers to the concept of
dividing a program into separate sub-programs or
modules. Each module can be developed, tested,
and maintained independently.
• Example: In a large software project, different
classes and functions can be organized into
modules, making it easier to manage and
understand.
Python Objects & Classes
• Class and Object:
– Class: A blueprint for creating objects (a particular data
structure), defining a set of attributes and methods that the
object created from the class will have.
• Create a Class
– To create a class, use the keyword class:
• Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5
print(MyClass)
Output 🡺 <class '__main__.MyClass'>
Python Objects & Classes
p1 = Person(“Piter", 36)
print(p1.name)
print(p1.age)
• Output 🡺 Piter
36
Doc string for classes
• A docstring is a special type of comment in
Python that is used to describe the purpose
and functionality of a class, method, or
function. When placed inside a class, it helps
explain what the class does, what attributes it
has, and what methods it includes. Docstrings
are important for making code easier to
understand and maintain, especially for others
who may work with the code later.
Doc string for classes
class Student:
"""
A simple class to represent a student.
Attributes:
----------
name : str
The student's name.
student_id : int
The student's ID number.
grades : list of float
The student's grades.
"""
• In this example:
• make, model, and year are member variables of the Car
class.
• Each instance of Car will have its own values for these
variables. For instance, my_car.make stores the value
"Toyota".
• Key Points:
• Member variables are defined within a class and are
typically initialized within the __init__ method.
• They are accessed using the self keyword, which refers to
the instance of the class.
• Each instance of the class can have different values for these
variables.
Doc string for classes
class Student:
"""
A simple class to represent a student.
Attributes:
----------
name : str
The student's name.
student_id : int
The student's ID number.
grades : list of float
The student's grades.
"""
stu1 = Student("Rahul",1001,"Nagpur")
stu1.display_info()
Output🡺 Name : Rahul
ID : 1001
Address : Nagpur
Doc string for classes
def stu_info(self):
print("Student section is:", self.section)
print("Student Roll Number is:", self.roll)
print("Student Address is:", self.add)
stu_1.stu_info()
Output 🡺 Student section is: A
Student Roll Number is: 101
Student Address is: Nagpur
Public & Private Members
• Private Members: These are variables or methods in a class that are intended to be
accessed only within the class itself. They are indicated by a leading underscore (_)
for a weak private indication or by double leading underscores (__) for stronger
privacy through name mangling.
Example:
class Employee:
def __init__(self):
self.emp_id = "[email protected]"
self.__emp_pass = 1080 # Private attribute
# Usage
Fruit1 = Fruits("Apples") # Creates a new Person object with the name
"Alice"
print(Fruit1.name) # Outputs: Apples
Dunder Method : __str__
class Student:
def __init__(self, name,roll_no):
self.name= name
self.roll_no = roll_no
def __str__(self):
return f" Student Name is : {self.name} \n Roll
Number is : {self.roll_no}"
# Usage
stu = Student("Rahul", 1001)
print(stu)
Dunder Method : __repr__
• __repr__: Official String Representation
• Purpose: This method returns a string that clearly describes the object and can be
used to create the same object again.
• Example:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __repr__(self):
return f"Car(make='{self.make}', model='{self.model}', year={self.year})"
# Usage
my_car = Car("Tata", “Punch", 2022)
print(repr(my_car))
Outputs: Car(make=‘Tata', model=‘Punch', year=2022)
Dunder Method : __add__:
__add__: Addition with +
Purpose: Defines what happens when you use the + operator on your objects.
Automatically called when you use + between two objects.
Example :
class Number:
def __init__(self, value):
self.value = value
def __str__(self):
# Returns the number as a string
return str(self.value)
# Usage
num1 = Number(10)
num2 = Number(20)
result = num1 + num2 # Adds num1 and num2 using the __add__ method
print(result) # Outputs: 30
Dunder Method
• Summary
• __str__: Defines the string that is printed out when the
object is printed.
• __repr__: Gives a detailed string representation of the
object, often used for debugging.
• __len__: Lets you define how the length of an object is
calculated.
• __eq__: Allows you to compare two objects with ==.
• __add__: Allows you to add two objects together using +.
• These are some of the most common and useful dunder
methods that help customize how your objects behave in
basic operations.
Operator Overloading
• If we will use same operator in different
purpose then it is called operator overloading.
• For example: + operator will perform addition
on two numbers, merge two lits or cocatenate
two strings.
• We will use corresponding magix=c method to
overload operator.
Operator Overloading
# Operator overloading without magic method will get error
class Employee:
def __init__(self,sal):
self.sal=sal
class Student:
def __init__(self,pkt_money):
self.pkt_money=pkt_money
e=Employee(35000)
s=Student(5000)
def __add__(self,other):
return self.sal+other.pkt_money
class Student:
def __init__(self,pkt_money):
self.pkt_money=pkt_money
e=Employee(35000)
s=Student(5000)
def bark(self):
return "Woof!"
def get_info(self):
return f"{self.name} is {self.age} years old."