0% found this document useful (0 votes)
16 views21 pages

Unit 4 CS

This document provides an overview of Object-Oriented Programming (OOP) in Python, detailing key concepts such as classes, objects, methods, inheritance, polymorphism, data abstraction, encapsulation, and data hiding. It explains the use of 'self' in class instances, constructors, and methods, along with examples demonstrating these principles. Additionally, it covers error handling in Python, including syntax errors, logical errors, and the use of try-except blocks for managing exceptions.

Uploaded by

mdnyaneshwar390
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)
16 views21 pages

Unit 4 CS

This document provides an overview of Object-Oriented Programming (OOP) in Python, detailing key concepts such as classes, objects, methods, inheritance, polymorphism, data abstraction, encapsulation, and data hiding. It explains the use of 'self' in class instances, constructors, and methods, along with examples demonstrating these principles. Additionally, it covers error handling in Python, including syntax errors, logical errors, and the use of try-except blocks for managing exceptions.

Uploaded by

mdnyaneshwar390
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

UNIT 4

OBJECT ORIENTED PROGRAMMING OOP IN


PYTHON
Introduction:
Like other general-purpose programming languages, Python is also an object-oriented language
since its beginning. It allows us to develop applications using an Object-Oriented approach.
In Python, we can easily create and use classes and objects.

An object-oriented paradigm is to design the program using classes and objects. The object is
related to real-word entities such as book, house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread technique to solve the problem by creating objects.

Major principles of object-oriented programming system are given below.

o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation

Class
o The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.

Syntax

1. class ClassName:
2. <statement-1>
3. .
4. .
5. <statement-N>

What is the use of self in Python?

When working with classes in Python, the term “self” refers to the instance of the
class that is currently being used. It is customary to use “self” as the first parameter
in instance methods of a class. Whenever you call a method of an object created
from a class, the object is automatically passed as the first argument using the “self”
parameter. This enables you to modify the object’s properties and execute tasks
unique to that particular instance.
 Python3

class mynumber:

def __init__(self, value):

[Link] = value

def print_value(self):

print([Link])

obj1 = mynumber(17)

obj1.print_value()
Python Class self Constructor
When working with classes, it’s important to understand that in Python, a class
constructor is a special method named __init__ that gets called when you create an
instance (object) of a class. This method is used to initialize the attributes of the
object. Keep in mind that the self parameter in the constructor refers to the instance
being created and allows you to access and set its attributes. By following these
guidelines, you can create powerful and efficient classes in Python.

class Subject:

def __init__(self, attr1, attr2):

self.attr1 = attr1

self.attr2 = attr2

obj = Subject('Maths', 'Science')

print(obj.attr1)

print(obj.attr2)

Output:
Maths

Example: Creating Class with Attributes and Methods


This code defines a Python class car representing cars with attributes ‘model’ and
‘color’. The __init__ constructor initializes these attributes for each instance.
The show method displays model and color, while direct attribute access and method
calls demonstrate instance-specific data retrieval.
class car():

# init method or constructor

def __init__(self, model, color):

[Link] = model

[Link] = color

def show(self):

print("Model is", [Link] )

print("color is", [Link] )

# both objects have different self which contain their attributes

audi = car("audi a4", "blue")

ferrari = car("ferrari 488", "green")

[Link]() # same output as [Link](audi)

[Link]() # same output as [Link](ferrari)

print("Model for audi is ",[Link])


print("Colour for ferrari is ",[Link])

Output:
Model is audi a4
color is blue
Model is ferrari 488
color is green
Model for audi is audi a4
Colour for ferrari is green

Self in Constructors and Methods


Self is the first argument to be passed in Constructor and Instance [Link] must
be provided as a First parameter to the Instance method and constructor. If you don’t
provide it, it will cause an error.

# Self is always required as the first argument

class check:

def __init__():

print("This is Constructor")

object = check()

print("Worked fine")

# Following Error is produced if Self is not passed as an argument

Traceback (most recent call last):

File "/home/[Link]", line 6, in <module>


object = check()

TypeError: __init__() takes 0 positional arguments but 1 was given

Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the doc string defined in the function
source code.

When we define a class, it needs to create an object to allocate the memory. Consider the
following example.

Example:

1. class car:
2. def __init__(self,modelname, year):
3. [Link] = modelname
4. [Link] = year
5. def display(self):
6. print([Link],[Link])
7.
8. c1 = car("Toyota", 2016)
9. [Link]()

Output:

Toyota 2016

In the above example, we have created the class named car, and it has two attributes modelname
and year. We have created a c1 object to access the class attribute. The c1 object will allocate
memory for these values. We will learn more about class and object in the next tutorial.
Method
The method is a function that is associated with an object. In Python, a method is not unique to
class instances. Any object type can have methods.

Inheritance

Inheritance is the most important aspect of object-oriented programming, which simulates the
real-world concept of inheritance. It specifies that the child object acquires all the properties and
behaviors of the parent object.

By using inheritance, we can create a class which uses all the properties and behavior of another
class. The new class is known as a derived class or child class, and the one whose properties are
acquired is known as a base class or parent class.

Inheritance provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific implementation to
the functions of the parent class. In this section of the tutorial, we will discuss inheritance in
detail.

In python, a derived class can inherit base class by just mentioning the base in the bracket after
the derived class name. Consider the following syntax to inherit a base class into the derived
class.
Syntax

1. class derived-class(base class):


2. <class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.

1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>

Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. [Link]()
10. [Link]()

Output:

dog barking
Animal Speaking

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-
level inheritance is archived when a derived class inherits another derived class. There is
no limit on the number of levels up to which, the multi-level inheritance is archived in
python.
The syntax of multi-level inheritance is given below.

Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
7. .
8. .

Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. [Link]()
14. [Link]()
15. [Link]()

Output:

dog barking
Animal Speaking
Eating bread...

Method Overriding
We can provide some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific implementation,
then the concept is called method overriding. We may need to perform method overriding in the
scenario where the different definition of a parent class method is needed in the child class.

Consider the following example to perform method overriding in python.

Example
1. class Animal:
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. [Link]()

Output: Barking
Example of method overriding
1. class Bank:
2. def getroi(self):
3. return 10;
4. class SBI(Bank):
5. def getroi(self):
6. return 7;
7.
8. class ICICI(Bank):
9. def getroi(self):
10. return 8;
11. b1 = Bank()
12. b2 = SBI()
13. b3 = ICICI()
14. print("Bank Rate of interest:",[Link]());
15. print("SBI Rate of interest:",[Link]());
16. print("ICICI Rate of interest:",[Link]());

Output:

Bank Rate of interest: 10


SBI Rate of interest: 7
ICICI Rate of interest: 8

Data Hiding in Python

What is 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 also minimizes system complexity for increase
robustness by limiting interdependencies between software requirements. Data
hiding is also known as information hiding. In class, if we declare the data members
as private so that no other class can access the data members, then it is a process of
hiding data.
Data Hiding in Python:

The Python document introduces Data Hiding as isolating the user from a part of
program implementation. Some objects in the module are kept internal, unseen, and
unreachable to the user. Modules in the program are easy enough to understand how
to use the application, but the client cannot know how the application functions.
Thus, data hiding imparts security, along with discarding dependency. Data hiding
in Python is the technique to defend access to specific users in the application.
Python is applied in every technical area and has a user-friendly syntax and vast
libraries. 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.
Example:

class Solution:

__privateCounter = 0

def sum(self):

self.__privateCounter += 1

print(self.__privateCounter)

count = Solution()

[Link]()

[Link]()
# Here it will show error because it unable

# to access private member

print(count.__privateCount)

Output:
Traceback (most recent call last):
File "/home/[Link]", line 11, in
<module>
print(count.__privateCount)
AttributeError: 'Solution' object has no attribute '__privateCount'

To rectify the error, we can access the private member through the class name :

class Solution:

__privateCounter = 0

def sum(self):

self.__privateCounter += 1

print(self.__privateCounter)

count = Solution()
[Link]()

[Link]()

# Here we have accessed the private data

# member through class name.

print(count._Solution__privateCounter)

Output:
1
2

Advantages of Data Hiding:


1. It helps to prevent damage or misuse of volatile data by hiding it from the public.
2. The class objects are disconnected from the irrelevant data.
3. It isolates objects as the basic concept of OOP.
4. It increases the security against hackers that are unable to access important data.

Disadvantages of Data Hiding:


1. It enables programmers to write lengthy code to hide important data from
common clients.
2. The linkage between the visible and invisible data makes the objects work faster,
but data hiding prevents this linkage.

Errors and Exceptions in Python


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)

Syntax errors

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

Example

# initialize the amount variable

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

Output:

It returns a syntax error message because after the if statement a colon: is missing.
We can fix this by writing the correct syntax.
logical errors(Exception)

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
Zero Division Error exception is raised, or when we import a module that does not
exist then Import Error is raised.

Example 1:

# initialize the amount variable

marks = 10000

# perform division with 0

a = marks / 0

print(a)

Output:

In the above example the ZeroDivisionError as we are trying to divide a number by


0.
Handling Exception

Python Try Except


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

In Python, you use the try and except block to catch and handle exceptions. Python
executes code following the try statement as a normal part of the program. The code
that follows the except statement is the program’s response to any exceptions in the
preceding try clause:

When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try statement:

Example
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

#This will raise an exception, because x is not defined:

Example

print(x)

Output:

Python Raise an Exception


The raise statement in Python is used to raise an exception. Try-except blocks can be used to
manage exceptions, which are errors that happen while a programme is running. When an
exception is triggered, the programme goes to the closest exception handler, interrupting the
regular flow of execution.

o The raise keyword is typically used inside a function or method, and is used to indicate
an error condition.
o We can throw an exception and immediately halt the running of your programme by
using the raise keyword.
o Python looks for the closest exception handler, which is often defined using a try-except
block, when an exception is triggered.
o If an exception handler is discovered, its code is performed, and the try-except block's
starting point is reached again.
o If an exception handler cannot be located, the software crashes and an error message
appears.
An illustration of how to raise an exception is provided below:

Example-1:
Code

1. # Python program to raise an exception


2. # divide function
3. def divide(a, b):
4. if b == 0:
5. raise Exception(" Cannot divide by zero. ")
6. return a / b
7. try:
8. result = divide(10, 0)
9. except Exception as e:
10. print(" An error occurred: ", e)

Output:

An error occurred: Cannot divide by zero.

In this illustration, the division function accepts the inputs a and b, and if b equals zero, an
exception is raised. The try block catches this exception, and the unless block prints the error
message.

Python - User-Defined Exceptions

Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.

Here is an example that has a user-defined MyException class. Here, a class is created that is
subclassed from base Exception class. This is useful when you need to display more specific
information when an exception is caught.

In the try block, the user-defined exception is raised whenever value of num variable is less than
0 or more than 100 and caught in the except block. The variable e is used to create an instance of
the class MyException.
Example
class MyException(Exception):
"Invalid marks"
pass

num = 10
try:
if num <0 or num>100:
raise MyException
except MyException as e:
print ("Invalid marks:", num)
else:
print ("Marks obtained:", num)

Output

For different values of num, the program shows the following output −

Marks obtained: 10
Invalid marks: 104
Invalid marks: -10

You might also like