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

Unit 5

This document provides an overview of Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, objects, methods, inheritance, and exception handling. It explains the properties of objects, the use of self-variable, constructors, and magical methods, as well as different types of inheritance and data hiding. Additionally, it distinguishes between errors and exceptions, detailing how to handle exceptions using try and except blocks.

Uploaded by

godwineldho99
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 views12 pages

Unit 5

This document provides an overview of Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, objects, methods, inheritance, and exception handling. It explains the properties of objects, the use of self-variable, constructors, and magical methods, as well as different types of inheritance and data hiding. Additionally, it distinguishes between errors and exceptions, detailing how to handle exceptions using try and except blocks.

Uploaded by

godwineldho99
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
You are on page 1/ 12

UNIT V

OBJECT ORIENTED PROGRAMMING & EXCEPTION HANDLIN

Classes:
Python is a programming language that focuses on object-oriented
programming. In Python, almost everything is an object. We can check if the
python is an object using the type(). It is just a collection of variables and Python
functions. There are various types of objects in Python such as Lists, dictionaries,
files, sets, strings and etc. An object is defined by its class. For example, an integer
variable is a member of the integer class. An object is a physical entity. The
properties of an object are as follows. State, Identity, and behavior are the three
key properties of the object.
The definition of Python class is simply a logical entity that behaves as a prototype
or a template to create objects. Python classes provide methods that could be used
to modify an object’s state. They also specify the qualities that an object may
possess.

Ex:
a = 28
print(type(a))
#<class 'int'>
l = [1,2,3]
print(type(l))
#<class 'list'>

The new object belongs to the List class. From the object, we can call
methods, already pre-built in Python. To see all the methods allowed in the object,
we use the dir() function
dir(l)

What is a Class?

The class can be defined as a collection of objects that define the common
attributes and behaviors of all the objects.
What is an Object?

The object is an entity that has state and behavior. It is an instance of a class
that can access the data.

Self-Variable:

Here, the self is used as a reference variable, which refers to the current class
object. It is always the first argument in the function definition. However,
using self is optional in the function call.

class Employee:
id = 10
name = "Devansh"
def display (self):
print(self.id,self.name)

The self-parameter refers to the current instance of the class and accesses the
class variables. We can use anything instead of self, but it must be the first
parameter of any function which belongs to the class.

# Creating a emp instance of Employee class


emp = Employee()
emp.display()

Methods:

 A method is a function that is “associated” with an object.


 A class attribute refers to a Python variable that belongs to a class rather
than a specific object.
 The class can be assigned to a variable. Object instantiation is the term for
this.
 Using the dot operator, you’ll be able to access the characteristics included
within the class.
Syntax:.
class ClassName:
def method_name():
# Method_body

Constructor Method:

class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Josh')
p.say_hi()

Ex:
 Initializer method __init__, called in this way because it’s the method that
initializes the attributes of the object. Moreover, it is automatically called once
the object is created.
 Magical methods are special methods with double underscores on both sides. For
example, __add__ and __mul__ are used to respectively sum and multiplicate
objects of the same class, while __repr__ returns a representation of the object
as a string.
 Instance methods are methods that belong to the object created. For
example, l.append(4) adds an element at the end of the list.

In addition to the code shown previously, the initializer method __init__ is used to
initialize the attributes of the Dog class.

Initializer method

class Dog:
def __init__(self,name,breed,age):
self.Name = name
self.Breed = breed
self.Age = age
print("Name: {}, Breed: {}, Age: {}".format(self.Name,
self.Breed,self.Age))

jack = Dog('Jack','Husky',5)
print(jack)
print(jack.Age)

Magical Method

class Dog:
def __init__(self,name,breed,age):
self.Name = name
self.Breed = breed
self.Age = age
def __repr__(self):
return "Name: {}, Breed: {}, Age: {}".format(self.Name,
self.Breed,self.Age)
jack = Dog('Jack','Husky',5)
print(jack)

Instance Method

class Dog:
def __init__(self,name,breed,age,tired):
self.Name = name
self.Breed = breed
self.Age = age
self.Tired = tired
def __repr__(self):
return "Name: {}, Breed: {}, Age: {}".format(self.Name,
self.Breed,self.Age)
def Sleep(self):
if self.Tired==True:
return 'I will sleep'
else:
return "I don't want to sleep"

jack = Dog('Jack','Husky',5, tired=True)


print(jack.Sleep())

Inheritance:

In Python, there are different inheritance forms depending on the inheritance


pattern between a derived class and a base class. The following are some of the
inheritance types available in Python:

 Single inheritance: Single inheritance is the sort of inheritance in which a class


inherits only one base class.
 Multiple inheritances: Many inheritances refers to a situation in which a class
inherits from multiple base classes. Python, unlike other languages, ultimately
enables multiple inheritances. All of the base classes are listed as a comma-
separated list inside brackets.
 Multilevel inheritance: Multilevel inheritance is when a class inherits a base
class, and then another class inherits this previously derived class, resulting in a
parent-child relationship class structure.
 Hierarchical inheritance: Hierarchical inheritance occurs when several derived
classes inherit a single base class.
 Hybrid inheritance: Hybrid inheritance occurs when one or more of the
inheritances mentioned above types are combined.

Ex:
class polygon:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth

class square(polygon):
def __init__(self, side):
polygon.__init__(self, side, side)

MySquare = square(3)
print(MySquare.area())

Overriding Methods:

# Defining parent class


class Parent():

# Constructor
def __init__(self):
self.value = "Inside Parent"

# Parent's show method


def show(self):
print(self.value)
# Defining child class
class Child(Parent):

# Constructor
def __init__(self):
self.value = "Inside Child"

# Child's show method


def show(self):
print(self.value)

# Driver's code
obj1 = Parent()
obj2 = Child()

obj1.show()
obj2.show()

Method overriding with multiple and multilevel inheritance

Multiple Inheritance: When a class is derived from more than one base class it is
called multiple Inheritance.

# Defining parent class 1


class Parent1():

# Parent's show method


def show(self):
print("Inside Parent1")

# Defining Parent class 2


class Parent2():

# Parent's show method


def display(self):
print("Inside Parent2")

# Defining child class


class Child(Parent1, Parent2):
# Child's show method
def show(self):
print("Inside Child")

# Driver's code
obj = Child()

obj.show()
obj.display()

Multilevel Inheritance: When we have a child and grandchild relationship


# overriding in multilevel inheritance

class Parent():

# Parent's show method


def display(self):
print("Inside Parent")

# Inherited or Sub class (Note Parent in bracket)


class Child(Parent):

# Child's show method


def show(self):
print("Inside Child")

# Inherited or Sub class (Note Child in bracket)


class GrandChild(Child):
# Child's show method
def show(self):
print("Inside GrandChild")

# Driver code
g = GrandChild()
g.show()
g.display()
Using Super(): Python super() function provides us the facility to refer to the parent
class explicitly. It is basically useful where we have to call superclass functions. It
returns the proxy object that allows us to refer parent class by ‘super’.

# super()

class Parent():

def show(self):
print("Inside Parent")

class Child(Parent):

def show(self):

# Calling the parent's class


# method
super().show()
print("Inside Child")
# Driver's code
obj = Child()
obj.show()

Data Hiding:

Data hiding is a concept which underlines the hiding of data or information


from the user. It is one of the key aspects of Object-Oriented programming
strategies. It includes object details such as data members, internal work. Data
hiding excludes full data entry to class members and defends object integrity by
preventing unintended changes.
Data hiding in Python is performed using the __ double underscore before done
prefix. This makes the class members non-public and isolated from the other
classes.

Ex:

class CounterClass:
__privateCount = 0
def count(self):
self.__privateCount += 1
print(self.__privateCount)
counter = CounterClass()
counter.count()
counter.count()
print(counter.__privateCount)

counter.count()
counter.count()
print(counter.CounterClass__privatecounter)

Difference between an Error and Exception:


Error
Errors are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal events
occur which changes the normal flow of the program.

Two types of Error occurs in python.

1. Syntax errors
2. Logical errors (Exceptions)

 When the proper syntax of the language is not followed then a syntax error
is thrown.

amount = 10000

# check that You are eligible to purchase Dsa Self Paced or not
if(amount>2999)
print("You are eligible to purchase Dsa Self Paced")
When in the runtime an error that occurs after passing the syntax test is
called exception or logical type. For example, when we divide any number by zero
then the ZeroDivisionError exception is raised, or when we import a module that
does not exist then ImportError is raised.
# initialize the amount variable
marks = 10000

# perform division with 0


a = marks / 0
print(a)

Exception

 Exceptions are those which can be handled at the run time whereas errors
cannot be handled.
 In Python, we catch exceptions and handle them using try and except code
blocks. The try clause contains the code that can raise an exception, while
the except clause contains the code lines that handle the exception. Let's see
if we can access the index from the array, which is more than the array's
length, and handle the resulting exception.

Ex:
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyond
the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the
Python interpreter
except:
print ("Index out of range")

Handling Exception:

Raising Exceptions:
If a condition does not meet our criteria but is correct according to the
Python interpreter, we can intentionally raise an exception using the raise keyword.
We can use a customized exception in conjunction with the statement.

#Python code to show how to raise an exception in Python


num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is
{len(num)}" )

https://intellipaat.com/blog/tutorial/python-tutorial/python-classes-and-objects/
#no1
https://www.javatpoint.com/python-exception-handling

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy