0% found this document useful (0 votes)
8 views

UNIT-V_OOP_Python

The document provides an overview of Object-Oriented Programming (OOP) in Python, covering concepts such as classes, objects, inheritance, polymorphism, and exception handling. It explains how to define classes and create objects, as well as the principles of inheritance and polymorphism, including method overriding and overloading. Additionally, it touches on error handling in Python and introduces libraries for creating graphical user interfaces (GUIs).

Uploaded by

kruthikaml17
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)
8 views

UNIT-V_OOP_Python

The document provides an overview of Object-Oriented Programming (OOP) in Python, covering concepts such as classes, objects, inheritance, polymorphism, and exception handling. It explains how to define classes and create objects, as well as the principles of inheritance and polymorphism, including method overriding and overloading. Additionally, it touches on error handling in Python and introduces libraries for creating graphical user interfaces (GUIs).

Uploaded by

kruthikaml17
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/ 40

OBJECT ORIENTED PROGRAMMING IN

PYTHON
Introduction
• Python allows the users to program in procedural, functional and object-
oriented style.
• Why OOP in python?
Structuring a program so that properties and behaviors are bundled into
individual objects to reuse the code.
Class
Objects
OOPs Polymorphism
Concepts
in Python Encapsulation
Inheritance
Data Abstraction
Python Class
• A class is a collection of objects.
• A class contains the blueprints or the prototype from which the
objects are being created.
Python Class
• A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class.
• The attributes are data members (class variables and instance variables) and
methods, accessed through dot notation.
Python
Class
Python Class
• The argument self refers to the current instance of the class.
• Python adds the self argument automatically when we call the methods.
Python Object
• An object has two characteristics:
• attributes
• behavior
class Dog:
def __init__(self, name, age):
Attributes
self.name = name
self.age = age

def bark(self): Class


print(f"{self.name} says Woof!") • Dog1
Object
• Name , age
# Creating instances of the Dog class Dog
dog1 = Dog("Buddy", 3) • Dog2
dog2 = Dog("Max", 5) • Name,ge
# Accessing attributes and methods of the instances
print(f"{dog1.name} is {dog1.age} years old.")
dog1.bark()

print(f"{dog2.name} is {dog2.age} years old.")


dog2.bark()
class Parrot:

# class attribute
name = ""
age = 0

# create parrot1 object


parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10

# create another object parrot2


parrot2 = Parrot()
parrot2.name = "Woo"
parrot2.age = 15

# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
• The first method __init__() is a special method, which is called class
constructor or initialization method that Python calls when we create a new
instance known as object of this class.
INHERITANCE
• What is inheritance? In terms of programming
• Why inheritance? • Attributes
• properties • Methods
• characters
• behaviors
INHERITANCE
• A class’s ability to inherit/transfer methods Base/super
and/or characteristics from another class is
known as inheritance.

Derived/subclass
Syntax

class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Types of Inheritance

Single inheritance

Multiple Inheritance

Multilevel inheritance

Hierarchical Inheritance

Hybrid Inheritance
Single inheritance
• single or simple inheritance, a child class inherits from a single parent class.
There is one child class and one parent class.
Multilevel inheritance

• Multilevel inheritance is the process


where we inherit a class from a
derived class.
Hierarchical inheritance

• more than one child


class is derived from a
single parent class
Hybrid Inheritance
• Hybrid Inheritance is the mixture of
two or more different types of
inheritance.
POLYMORPHISM
• Polymorphism is an ability to use a common interface for multiple forms.
The term polymorphism in general means multiple forms of the same entity.
POLYMORPHISM
• The two forms of polymorphism in Python are :
• • Compile-time Polymorphism
A compile-time polymorphism also called as static polymorphism which gets resolved
during the compilation time of the program. One common example is “method
overloading”.
• • Run-time Polymorphism
A run-time Polymorphism is also, called as dynamic polymorphism where it gets
resolved into the run time. One common example of Run-time polymorphism is
“method overriding”.
Method Overriding
• Method overriding occurs when a subclass provides a specific
implementation for a method that is already defined in its superclass. The
method in the subclass should have the same name and parameters as the
method in the superclass.
class Animal:
def sound(self):
print("This animal makes a sound.")

class Dog(Animal):
# Overriding the 'sound' method
def sound(self):

Method Overriding print("The dog barks.")

# Creating objects
a = Animal()
d = Dog()

# Calling the methods


a.sound() # Output: This animal makes a sound.
d.sound() # Output: The dog barks.
Method Overloading
• Method overloading refers to defining multiple methods with the same
name but different parameter signatures (number or types of arguments).
However, Python does not support method overloading in the way that
some other languages (like Java) do. In Python, if you define multiple
methods with the same name, the last method defined will override the
others.
class Calculator:
# Using default arguments to simulate overloading
def add(self, a, b, c=0):
return a + b + c

# Creating an object
Method
calc = Calculator()
Overloading

# Calling the method with two arguments


print(calc.add(2, 3)) # Output: 5

# Calling the method with three arguments


print(calc.add(2, 3, 4)) # Output: 9
class MathOperations:
def add(self, a, b):
return a + b
def add(self, a, b, c):
return a + b + c
math = MathOperations()
# The last defined add method will be used
print(math.add(2, 3, 4))
Exception
• There are several built-in Python exceptions that can be raised
when an error occurs during the execution of a program.
• Errors detected during execution are called exceptions
Exception

SyntaxError: This exception is raised when the interpreter


encounters a syntax error in the code, such as a misspelled
keyword, a missing colon, or an unbalanced parenthesis.

TypeError: This exception is raised when an operation or


function is applied to an object of the wrong type, such as
adding a string to an integer.
Exception

NameError: This exception is raised when a variable or function name is not found in the current
scope.

IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence
types.

KeyError: This exception is raised when a key is not found in a dictionary.

ValueError: This exception is raised when a function or method is called with an invalid argument or
input, such as trying to convert a string to an integer when the string does not represent a valid integer.
Exception
AttributeError: This exception is raised when an attribute or method is not found on
an object, such as trying to access a non-existent attribute of a class instance.

IOError: This exception is raised when an I/O operation, such as reading or writing a
file, fails due to an input/output error.

ZeroDivisionError: This exception is raised when an attempt is made to divide a


number by zero.

ImportError: This exception is raised when an import statement fails to find or load a
module.
Python try...except Block
try:
# code that may cause exception
except:
# code to run when exception occurs
Example - 1
Example - 2
Example - 3

def div(a , b):


try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
Example - 4

try:
k = 5//0
print(k)

except ZeroDivisionError:
print("Can't divide by zero")

finally:
print('This is always executed')
Libraries in Python
• A library is a collection of precompiled codes that can be used
later in a program for some specific well-defined operations.
Python - GUI
• A graphical user interface (GUI) is a desktop interface that allows you to
communicate with computers.
• Tkinter
• wxPython
• PyQt
• PyGTK
• PySimpleGUI
• Pygame
Python GUI – tkinter
• Python tkinter is the fastest and easiest way to create GUI applications.
• To create a tkinter Python app:
• Importing the module – tkinter
• Create the main window (container)
• Add any number of widgets to the main window
• Apply the event Trigger on the widgets.

You might also like