0% found this document useful (0 votes)
9 views31 pages

Unit 3

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, polymorphism, abstraction, and modularity. It explains how these concepts are implemented in Python, detailing member variables, constructors, docstrings, public and private members, dunder methods, and operator overloading. Examples are provided to illustrate the creation and use of classes and objects in Python.

Uploaded by

ahakehimanshu9
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)
9 views31 pages

Unit 3

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, polymorphism, abstraction, and modularity. It explains how these concepts are implemented in Python, detailing member variables, constructors, docstrings, public and private members, dunder methods, and operator overloading. Examples are provided to illustrate the creation and use of classes and objects in Python.

Uploaded by

ahakehimanshu9
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/ 31

UNIT 3

Object Oriented
Concept
Features of Object Oriented
Programming

• Classes: A class is a blueprint or prototype


from which objects are created. It defines a
data type by bundling data and methods that
work on the data.
• Objects: An object is an instance of a class. It
is a real-world entity that has a state and
behavior defined by its class.
Features of Object Oriented
Programming
• Encapsulation:
– Encapsulation is the bundling of data (attributes) and
methods (functions) that operate on the data into a single
unit or class. It restricts direct access to some of the object’s
components, which is a means of preventing accidental
interference and misuse of the data.
– In Python, encapsulation is achieved through the use of
access modifiers. These access modifiers control the
visibility of class attributes and methods from outside the
class. The three common access modifiers are:
• Public: Members are accessible from outside the class.
• Protected: Members are accessible within the class and
its subclasses.
• Private: Members are only accessible within the class.
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

• Object: An instance of a class. When a class is defined,


only the description is defined. When an object is created,
memory is allocated.
• Create Object
– Now we can use the class named MyClass to create objects:
• Example
Create an object named p1, and print the value of x:
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
Output🡺 5
Member Variables
• What Are Member Variables?
– Member variables are like data storage spots inside an object.
– They hold information about the object, such as its characteristics
or properties.
• Where Do They Live?
– Member variables are defined inside a class.
– When you create an object from that class, it gets its own set of
these variables.
• Example to Make It Clear
• Imagine you have a blueprint to build a toy car. The blueprint is
the class, and each toy car you build from it is an object.
• The blueprint might have details like color, size, and speed.
• These details are the member variables.
Member Variable
• __init__ method in Python is used to initialize objects of a class. It is also called a
constructor.
• Like methods, a constructor also contains a collection of statements(i.e.
instructions) that are executed at the time of Object creation. It is run as soon as an
object of a class is instantiated.
• Example :
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age

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.
"""

def __init__(self, name, student_id,add):


"""
Initializes a student with a name and ID number.
"""
self.name = name
self.student_id = student_id
self.add = add
Member Variables
• Example :
• class Car:
def __init__(self, make, model, year):
# These are member variables
self.make = make
self.model = model
self.year = year
def display_info(self): # Function
print(f"Car color : {self.color}")
print(f"Car Model: {self.model}")
print(f"Car Year: {self.year}")
Member Variable
• # Create an instance of the Car class
my_car = Car("Tata", “Altroz", 2022)
# Accessing member variables
print(my_car.make) # Output:Tata
print(my_car.model) # Output: Altroz
print(my_car.year) # Output: 2022
# Calling a method that uses member variables
my_car.display_info()
Member Variable

• 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.
"""

def __init__(self, name, student_id,add):


"""
Initializes a student with a name and ID number.
"""
self.name = name
self.student_id = student_id
self.add = add
Doc string for classes
def display_info(self):
"""
Prints the student's details.
"""
print("Name : " , self.name)
print("ID : " ,self.student_id)
print("Address : ",self.add)

stu1 = Student("Rahul",1001,"Nagpur")
stu1.display_info()
Output🡺 Name : Rahul
ID : 1001
Address : Nagpur
Doc string for classes

• The print.__doc__ attribute in Python contains the


docstring for the print function, which provides a brief
description of what the function does and its parameters.
Here's what the print.__doc__ typically returns:
• Example : print(print.__doc__)
• Output 🡺 print(value, ..., sep=' ', end='\n', file=sys.stdout,
flush=False) Prints the values to a stream, or to sys.stdout
by default. Optional keyword arguments: file: a file-like
object (stream); defaults to the current sys.stdout. sep:
string inserted between values, default a space. end: string
appended after the last value, default a newline. flush:
whether to forcibly flush the stream.
Public and Private Members
• Public Members : These are variables or methods in a class that can be accessed from anywhere, both inside and
outside of the class. They are defined without any leading underscores.
• Example:
class Student:
def __init__(self, section, roll, add):
self.section = section
self.roll = roll
self.add = add

def stu_info(self):
print("Student section is:", self.section)
print("Student Roll Number is:", self.roll)
print("Student Address is:", self.add)

# Creating an instance of the Student class


stu_1 = Student("A", 101, "Nagpur")

# Accessing attributes and methods

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

# Creating an instance of the Employee class


emp_1 = Employee()
print(emp_1.emp_id)
print(emp_1.__emp_pass)
Output 🡺 [email protected]
AttributeError: 'Employee' object has no attribute '__emp_pass'
Dunder Method
• What is a Dunder Method?
• A dunder method (short for "double underscore") is a
special function in Python that starts and ends with
double underscores (__). These methods are
automatically used by Python to perform basic tasks,
like creating a new object.
• Basic Dunder Method Example: __init__
• What is __init__?
• __init__ is a special method that runs automatically
when you create a new object from a class.
• It helps to set up the object by initializing its attributes
(like setting a name or an age).
Dunder Method:__init__
Example :
class Fruits:
"""
A very simple class to represent a Fruits.
"""

def __init__(self, name):


"""
Initializes the Fruits with a name.
"""
self.name = name # Store the name in the object

# 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 __add__(self, other):


# Adds the values of two Number objects
return Number(self.value + other.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)

# add emp_sal + pkt_money


print(e+s)
Output 🡺 TypeError: unsupported operand type(s) for +: 'Employee' and 'Student‘.
Operator Overloading
• # Operator overloading with magic method to overcome the error
class Employee:
def __init__(self,sal):
self.sal=sal

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)

# add emp_sal + pkt_money


print(e+s)
Output 🡺 40000
Designing custom classes
class Dog:
def __init__(self, name, age):
self.name = name # The dog's name
self.age = age # The dog's age

def bark(self):
return "Woof!"

def get_info(self):
return f"{self.name} is {self.age} years old."

# Creating a Dog object


my_dog = Dog(“Pupii", 1)

# Making the dog bark


print(my_dog.bark()) # Output: Woof!

# Getting information about the dog


print(my_dog.get_info()) # Output: Pupii is 1 years old.

You might also like