0% found this document useful (0 votes)
83 views58 pages

Unit-4 OOP 26june24

Uploaded by

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

Unit-4 OOP 26june24

Uploaded by

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

Unit-4

Object Oriented Programming


Introduction
• Given any problem, the approach used to solve the problem
programmatically is called a programming paradigm.
• There are 2 types of paradigms:
• Procedural Programming,
• Object Oriented Programming and
• Python adopts the features of both procedural and object-oriented
programming paradigms, hence it is called a hybrid programming
language.
Procedure Oriented Programming
• Procedure-oriented paradigm uses a linear top-down approach and treats
data and procedures as two different entities.

• Based on the concept of a procedure call, Procedural Programming divides


the program into procedures, which are also known as routines or functions,
simply containing a series of steps to be carried out.
• Advantages:
• Procedural Programming is excellent for general-purpose programming.
• The code can be reused in different parts of the program, without the need to
copy it.
• The program flow can be tracked easily.
Sub-dividing the problem
• As programs get more complex and grow in size, it becomes extremely
important to write code that is easy to understand.
• A programmer can never keep a million-line program in mind at the same
time to debug errors.
• Hence, there is a need to break large programs into multiple smaller pieces
that are easier to manage and debug.
• A better approach to this would be to use object-oriented approach.
Object Oriented Programming
• We create classes in object-oriented programming.
• A class contains both data and functions.
• When we want to create something in memory, we create an object, which
is an instance of that class.
• So, for example, we can declare a Customer class, which holds data and
functions related to customers.
• Then, If we want our program to create a customer in memory, we create a
new object of the Customer class.
Advantages:
• Modularity for easier troubleshooting
• Reuse of code through inheritance
• Flexibility through polymorphism
• Effective problem solving
Our First Python Object
• An object can contain a number of functions (which we call
“methods”) as well as data that is used by those functions.
• We call data items that are part of the object “attributes”.
• We use the class keyword to define the data and code that will make
up each of the objects.
• The class keyword includes the name of the class and begins an
indented block of code where we include the attributes (data) and
methods (code).
• Each method looks like a function,
starting with the def keyword and
consisting of an indented block of code.
This example has one attribute (x) and
one method (party).
• The methods have a special first
parameter that we name by convention
self.
• an = PartyAnimal() This is where we
instruct Python to construct (e.g. create)
an object or “instance of the class named
PartyAnimal”.
• It looks like a function call to the class
itself and Python constructs the object
with the right data and methods and
returns the object which is then assigned
• We use an to access the code and data for that particular instance of
a PartyAnimal object.
• Each Partyanimal object/instance contains within it a variable x and
a method/function named party.
• When the party method is called, the first parameter (which we call
by convention self) points to the particular instance of the
PartyAnimal object that party is called from within.
• Within the party method, we see the line: self.x = self.x + 1
• This syntax using the ‘dot’ operator is saying ‘the x within self’. So
each time party() is called, the internal x value is incremented by 1
and the value is printed out.
• The following line is another way to call the party method within an
object:
• PartyAnimal.party(an)
• In this variation, we are accessing the code from within the class and
explicitly passing the object pointer an in as the first parameter (i.e.
self within the method). You can think of an.party() as shorthand for
the above line.
Python- Objects and Classes
• Python allows us to define classes to create objects.
• A class is a collection of instance variables and its related methods
that define an object type.
• A class is a blueprint or a template that defines a set of attributes
that characterize an object.
• Class variable − A variable that is shared by all instances of a class.
Class variables are defined within a class but outside any of the
class's methods. Class variables are not used as frequently as
instance variables are.
• Instance variable − A variable that is defined inside a method and
belongs only to the current instance of a class.
• Method − A special kind of function that is defined in a class
definition.
• Object − A unique instance of a class. An object comprises
both data members (class variables and instance variables)
and methods.
Applications
Classes and objects are frequently used in real-world applications like

• Web Development,
• Game Development,
• Scientific and Numeric Applications,
• Artificial Intelligence and Machine Learning,
• Software Development,
• Enterprise-level/Business Applications,
• Education programs and training courses,
• Language Development etc.
Python class:
•Classes are created by keyword class.
•Attributes are the variables that belong to a class.
•Attributes can be accessed using the dot (.) operator.
• Classes define functions called methods, which identify the behaviors and
actions that an object created from the class can perform with its data.
• Methods can be accessed using dot(.) operator.
• We can access the class attribute via instances of the class or via
the class name: object_name.class_attribute or class_name.class_attribute

Class Definition Syntax:


class ClassName:
# Statement-1
...
# Statement-N
Python class:

• A method is a function that is bound to an instance of a class.


• A method is an instance of the method class.
• A method has the first argument (self) as the object to which it is
bound.
• Python automatically passes the bound object to the method as the
first argument. By convention, its name is self.
• We can access methods using object - Object_name.method_name()
Object Lifecycle
• The lifecycle of an object starts from its creation or construction and
ends with its destruction.
• The object creation is done with the help of a special method called
constructor and destruction takes place with the help of a destructor
method.
• A constructor is a special type of method which is used to initialize
the instance members of the class.
Syntax of constructor declaration:
def __init__(self):
# body of the constructor
Object Lifecycle (Contd..)
• __init__ is called automatically when Example:
an object is created from a class and class Person:
allows us to initialize the attributes of # init method or constructor
the object. def __init__(self, name):
• “__init__” stands for “initialize.” self.name = name
• While giving the definition for an
__init__(self) method, a default # Sample Method
parameter, named 'self' is always def say_hi(self):
passed in its argument. print('Hello, my name is', self.name)
• This self represents the object of the
class itself. # Creating different objects
p1 = Person('Nikhil’)
p2 = Person('Abhinav’)
Output: p1.say_hi()
Hello, my name is Nikhil p2.say_hi()
Hello, my name is Abhinav
Object Lifecycle (Contd..)
• Destructors are called when an object gets destroyed.
• Python has a garbage collector that handles memory management
automatically.
• The __del__( ) method is known as a destructor method in Python. It
is called when all references to the object have been deleted i.e.,
when an object is garbage collected.

Syntax of destructor declaration:


def __del__(self):
# body of destructor
Object Lifecycle (Contd..)
• Python automatically calls Example:
__del__() when a given object is class Employee:
about to be destroyed by the # Initializing
garbage collector. def __init__(self):
• This call allows the object to print('Employee object created’)
release external resources and
clean itself up. # Calling destructor
def __del__(self):
Output: print("Destructor called")
Employee object created
Program Ended...
Destructor called
obj = Employee()
print('Program Ended...’)
Python user defined class example
class Person:
def __init__(self, name, age):
self.name=name
self.age=age

p1=Person(“John”, 30)
print(p1.name)
print(p2.age)

Output:
John
30
Difference b/w class & instance attributes

• Class attributes are variables that are associated with a class rather
than with instances (objects) of that class.
• Class attributes are shared among all instances of a class and are
defined within the class itself.
• Instance attributes are variables that belong to an instance of a
class.
• Each instance attribute is specific to a particular object created from
that class.
• These attributes define the characteristics or properties of individual
objects.
Aspect Class Attributes Instance Attributes
Defined within the class block but Defined within methods, typically
Definition outside of methods the __init__ constructor
Shared among all instances of the
Scope class Specific to each instance of the class

Accessed using the class name or any


Access instance Accessed using an instance of the class

Changing affects all instances of the


Modification class Changing affects only the specific instance

Storage
Location Stored in the class namespace. Stored in the instance namespace.

Define properties common to all


Usage Define properties specific to each instance
instances
Example python MyClass.class_attribute python instance_name.instance_attribute
Class Variables and Instance Variables
Class Example
class Person:
species = "Homo sapiens"
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hi, I'm {self.name}, {self.age} years old.")
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(f"All humans belong to the species: {Person.species}")
Output:
person1.introduce() All humans belong to the species: Homo sapiens
person2.introduce() Hi, I'm Alice, 25 years old.
Hi, I'm Bob, 30 years old.
• A program to create a class called Employee.
class Employee:
def __init__(self, name, age, job_title, salary):
self.name = name
self.age = age
self.job_title = job_title
self.salary = salary

def print_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
Output:
print(f"Job Title: {self.job_title}")
print(f"Salary: {self.salary}") Name: John Smith
Age: 30
employee1 = Employee("John Smith", 30, "Software Engineer“, 50000) Job Title: Software Engineer
employee1.print_info() Salary: 50000
Built-in Objects
• First line is constructing an object of type list,
stuff = list()
• Second and third lines are calling the append()
stuff.append('python') method.
• Fourth line is calling the sort() method, and
stuff.append('chuck')
• the fifth line is retrieving the item at position 0.
stuff.sort() • The sixth line is calling the __getitem__()
print (stuff[0]) method in the stuff list with a parameter of zero.
• The seventh line is a way of retrieving the 0th
print (stuff.__getitem__(0)) item in the list.
print (list.__getitem__(stuff,0)) • The last three lines of the program are
completely equivalent.
Fundamental Principles of object-oriented
programming
• Class
• Objects
• Inheritance
• Polymorphism
• Data Abstraction
• Encapsulation
Fundamental Principles of object-oriented programming (Contd.)
o Class
A class is a collection of objects. A class contains the blueprints or the prototype from
which the objects are being created. It is a logical entity that contains some attributes and
methods.
o Object
The object is an entity that has a state and behaviour associated with it. It may be any real-
world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point
numbers, even arrays, and dictionaries, are all objects.
An object consists of:
 State: It is represented by the attributes of an object. It also reflects the properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other objects.
Fundamental Principles of object-oriented programming (Contd.)
o Inheritance
• Inheritance allows a class to inherit the properties and methods of another
class called the parent class, the base class, or the super-class.
• The class that inherits is called the child class or sub-class.
• It helps to avoid duplication of codes by allowing code reuse as we need not
define the same methods and properties present in a super-class in the sub-
classes again.
• The sub-class can simply inherit them.
Fundamental Principles of object-oriented programming (Contd.)

o Polymorphism
• The word polymorphism means to have many forms. So, by using
polymorphism, you can add different meanings to a single component.
• There are two types of polymorphism:
 Run-time polymorphism
 Compile-time polymorphism
Fundamental Principles of object-oriented programming (Contd.)
 Method Overloading
 Methods overloading is a type of compile-time polymorphism using which you can define
various functions with the same name but different numbers of arguments. The function call is
resolved at compile time, so it's a type of compile-time polymorphism.
Example:
 You can create a function “add”. Now, when you pass two integers to this function, it will
return their sum, while on passing two strings, it will return their concatenation.
 So, the same function acts differently depending on the input data type.
• Method Overriding
• Method Overriding is a type of run-time polymorphism. It allows overriding a parent class’s
method by a child class. Overriding means that a child class provides a new implementation
of the same method it inherits from the parent class.
• These function calls are resolved at run-time, so it's a type of runtime polymorphism.
Example:
• You can have a parent class called “Shape” with a method named “findArea” that calculates
and returns the area of the shape. Several sub-classes inherit from the “Shape,” like Square,
Circle, Rectangle, etc. Each of them will define the function “findArea” in its way, thus
overriding the function.
Fundamental Principles of object-oriented programming (Contd.)
o Data Abstraction
• It hides unnecessary code details from the user. When we do not want to give out sensitive
parts of our code implementation to users.
Example: when you toggle a switch, it simply turns on or off the lights. Here, we only know the
functionality of the switch, but we don’t know its internal implementation, like how it works.
o Encapsulation
o It describes the idea of wrapping data and the methods that work on data within one unit.
This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can only
be changed by an object’s method. Those types of variables are known as private variables.
o A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.
Fundamental Principles of object-oriented programming (Contd.)

Encapsulation (Contd..)

Example:
• You can have some private variables in a class that you can't access outside the class for
security reasons. Now, to read or change the value of this variable, you can define public
functions in the class which will perform the read or writes operations.

Note:

• Data abstraction and encapsulation both are often used as synonyms.

• Both are nearly synonyms because data abstraction is achieved through encapsulation.
Inheritance
• One of the core concepts in object-oriented programming (OOP)
languages is inheritance.
• It is a mechanism that allows us to create a hierarchy of classes that
share a set of properties and methods.
• When one class inherits from another, it automatically takes on all the
attributes and methods of the first class but is also free to define new
attributes and methods of its own.
• The original class is called the parent class or base class or super class,
and the new class is the child class or derived class or sub class.
Advantages of Inheritance
• It represents real-world relationships well.
• It provides the reusability of a code. Repeating the same
code again in another class is avoided as well, more features
can be added without modifying existing ones.
• It is transitive in nature, which means that if class B inherits
from another class A, then all the subclasses of B would
automatically inherit from class A.
• Inheritance offers a simple, understandable model structure.
• Development and maintenance expenses are comparatively
reduced.
Python Inheritance Syntax
class BaseClass:
{Body}
class DerivedClass (BaseClass):
{Body}

- An object of derived class can access the base class methods also.
- But an object of base class cannot access derived class methods.
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')

# Derived class
class Car(Vehicle):
def car_info(self):
print('Inside Car class') Output
Inside Vehicle class
# Create object of Car Inside Car class
car = Car()

# access Vehicle's info using car object


car.Vehicle_info()
car.car_info()
The __init__( ) Method for a Child Class
• The first task Python has when creating an instance from a child class
is to assign values to all attributes in the parent class.

• To do this, the __init__() method for a child class needs help from its
parent class.
• Example:
• Let us model the Electric Car. It is a specific type of a car.
• Hence, we can have a base class as Car and a derived-class as
Electric_Car.
class Car:
"""A simple attempt to represent a car.""" def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
def __init__(self, manufacturer, model, year): self.odometer_reading += miles
"""Initialize attributes to describe a car."""
self.manufacturer = manufacturer class ElectricCar(Car):
self.model = model """Represent aspects of a car, specific to electric
self.year = year vehicles."""
self.odometer_reading = 0
def __init__(self, manufacturer, model, year):
def get_descriptive_name(self): """Initialize attributes of the parent class."""
"""Return a neatly formatted descriptive name.""" super().__init__(manufacturer, model, year)
long_name = f"{self.year} {self.manufacturer}
{self.model}"
return long_name.title() my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on
it.")

2019 Tesla Model S


The super() method in python
• In Python, the super() function is used to refer to the parent class
or superclass.
• It allows you to call methods defined in the parent class from the
child class.
• Syntax: super()
Returns a proxy object which represents the parent’s class.
super().__init__() line tells Python to call the __init__() method
from ElectricCar’s parent class, which gives an ElectricCar instance
all the attributes of its parent class.
The name super comes from a convention of calling the parent
class a superclass and the child class a subclass
Operator overloading

• In Python, we can change the way operators work for user-


defined types.
• For example, the + operator will perform arithmetic addition
on two numbers, merge two lists, or concatenate two strings.
• This feature in Python that allows the same operator to have
different meaning according to the context is called operator
overloading.
How to overload the operators in Python?
• Consider that we have two objects which are a physical representation of a class
(user-defined data type) and we have to add two objects with binary ‘+’ operator
it throws an error, because compiler don’t know how to add two objects.
• So we define a method for an operator and that process is called operator
overloading.
• We can overload all existing operators but we can’t create a new operator.

• To perform operator overloading, Python provides some special function or


magic function that is automatically invoked when it is associated with that
particular operator.
• For example, when we use + operator, the magic method __add__ is
automatically invoked in which the operation for + operator is defined.
Overloading binary + operator in Python:
• Functions that begin and end with double underscore “__” are called special
functions in python. They perform special tasks.
• when we want to overload any of the operators, we need to implement the
special functions in the user-defined data type.
• When we use an operator on user-defined data types then automatically a
special function or magic function associated with that operator is invoked.
• We can define methods in our class and operators work according to that
behaviour defined in methods.
• When we use + operator, the magic method __add__ is automatically invoked
in which the operation for + operator is defined.
• So by changing this magic method’s code, we can give extra meaning to the +
operator.
How Does the Operator Overloading Actually work?
Overloading the + operator

class A:
Whenever we change the behaviour of def __init__(self, a):
the existing operator through operator self.a = a
overloading, we have to redefine the # adding two objects
special function that is invoked def __add__(self, o):
automatically when the operator is used return self.a + o.a
with the objects. ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")
print(ob1 + ob2)
print(ob3 + ob4)
Complex number addition
• Create a class called complex, define a parameterized constructor to initialize real and
imaginary parts.
• Overload the + operator to add 2 given complex numbers and assign it to the third complex
number.
Overloading the less-than-operator <
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# overload < operator


def __lt__(self, other):
return self.age < other.age

p1 = Person("Alice", 20)
p2 = Person("Bob", 30)

print(p1 < p2) # prints True


print(p2 < p1) # prints False
Class Methods
• Class methods are methods that are called on the class itself, not on a
specific object instance. Therefore, it belongs to a class level, and all
class instances share a class method.
• A class method is bound to the class and not the object of the class. It
can access only class variables.
• It can modify the class state by changing the value of a class variable
that would apply across all the class objects.
• In method implementation, if we use only class variables, we should
declare such methods as class methods.
• The class method has a cls as the first parameter, which refers to the
class.
• The class method can be called using ClassName.method_name() as
well as by using an object of the class.
Examples
1. Develop a Python program to create a class Student with instance variables
usn, name and marks. Create two objects and display the details of the students
who has got the highest mark.
2. Develop a Python program to create a class Actor with instance variables
actorid, actorname, no_movies and earnings. Create three actors and display the
details of the actor whose average earning is the minimum.
3. Develop a Python program which creates the class Circle that has member
radius. Include methods to do the following.
a. Accept the radius from the user
b. Find the area of the circle
c. Find the perimeter of the circle
d. Display all the details
4. Develop a Python program to create a class Employee with members
empid, empname, empnohrs, empbasic, emphra(%), empda(%),empit(%),
empgross. Include methods to do the following:
a. Accept all values from the user. Note House rent allowance,
dearness allowance and income tax are given in %
b. Calculate the gross salary based on the formula
empgross= empbasic + empbasic*emphra + empbasic*empda -
empbasic*empit
c. Consider the overtime amount to be Rs.100 per hour. If empnohrs
>200, for every hour the employee is to be given additional payment.
Calculate the additional payment and update the gross. If empnohrs<200,
reduce Rs.100 per hour and update the gross.
5. A Multispeciality hospital wants to calculate the bill amount to be
paid by patients visiting the hospital. Bill amount includes consultation
fees and lab charges. Write a Python program to implement the class
with members- bill_id, patient_name and bill_amount. Include
methods of form:
a. __init__(bill_id, patient_name)
b. Calc_billamt (consultation_fees, labcharges)
c. Display the details – bill_id, patient_name and bill_amount
A discount of 10% can be given if the lab charges exceed Rs.25000. 5%
Discount can be given if lab charges exceeds Rs.10000/-
Examples
• Develop a Python program using class variables to count the number of
objects getting created for a class and display the same.
• Develop a Python program to create a class Player with member
variables name, matches_played. Derive a class Batsman from Player.
Class Batsman has a member variable runs_scored. Create a Batsman
object. Calculate and display the average runs scored by the Batsman.
• Develop a Python program to create a class Person with members –
name and age. Derive another class Patient with members pid and
doctorname. The program should include the following functionalities.
- Accept a patient id and display his/her details.
- Accept the name of the patient and display the names of the
doctor treating him/her.
class Player:
def __init__(self,name,matches):
self.name=name
self.matches_played=matches
class Batsman(Player):
def __init__(self,name,matches,runs):
super().__init__(name,matches)
self.runs=runs
def avg(self):
self.avg=self.runs/self.matches_played

b1=Batsman('Rahul',50,6000)
b1.avg()
print("Average runs scored by ",b1.name,":",b1.avg)
Example
• Develop a Python program to create a class Time with data
members – hours and minutes. Include the following methods:
• A parameterized constructor to set values to the hours and
minutes,
• A method ‘accept’ to accept the values for the members from the
user.
• Overload the + operator to add two given times. Ex. If Time1 has
hours=11 minutes=50 and Time2 has hours =4 minutes =40, then
Time3 should be hours=16 minutes=30
• A method to display the all the time objects.
• Create two objects of class Time and assign the sum of these two
objects to a third object.

You might also like