You are on page 1of 48

Unit: 4

OOP and File Handling

Prepared by: Ms. Parveen Mor Dahiya


OOP with Python?
 Python is a multi-paradigm programming language. Meaning, it supports
different programming approach.
 One of the popular approach to solve a programming problem is by creating
objects. This is known as Object-Oriented Programming (OOP).
An object has two characteristics:
 attributes
 behaviour

Let's take an example:


 Parrot is an object,
 name, age, color are attributes
 singing, dancing are behaviour
 The concept of OOP in Python focuses on creating reusable code. This concept
is also known as DRY (Don't Repeat Yourself).
...
In Python, the concept of OOP follows some basic principles:
 Inheritance:
A process of using details from a new class without modifying existing
class.
 Encapsulation:
Hiding the private details of a class from other objects.
 Polymorphism:
A concept of using common operation in different ways for different
data input
Python class?
 A class is a blueprint for the object.
 We can think of class as an sketch of a parrot with labels. It contains all
the details about the name, colors, size etc. Based on these descriptions,
we can study about the parrot. Here, parrot is an object.
The example for class of parrot can be :
class Parrot:
pass
 Here, we use class keyword to define an empty class Parrot. From
class, we construct instances. An instance is a specific object created
from a particular class.
Object
 An object (instance) is an instantiation of a class. When class is
defined, only the description for the object is defined. Therefore, no
memory or storage is allocated.
The example for object of parrot class can be:
obj = Parrot()
 Here, obj is object of class Parrot.
 Suppose we have details of parrot. Now, we are going to show how to
build the class and objects of parrot.
Creating Class and Object in Python
Attributes
The instance attributes
 These are object-specific attributes defined as parameters to the __init__ method. Each object can have
different values for themselves.
 In the below example, the “attrib1” and “attrib2” are the instance attributes.

class BookStore:
def __init__(self, attrib1, attrib2):
self.attrib1 = attrib1
self.attrib2 = attrib2

The class attributes


 Unlike the instance attributes which are visible at object-level, the class attributes remain the same for all
objects.
class BookStore:
instances = 0
def __init__(self, attrib1, attrib2):
self.attrib1 = attrib1
self.attrib2 = attrib2
BookStore.instances += 1
b1 = BookStore("", "")
b2 = BookStore("", "")
print("BookStore.instances:", BookStore.instances)
Methods
 Methods are functions defined inside the body of a class. They are used
to define the behaviours of an object.
__init__ :
 "__init__" is a reserved method in python classes. It is known as a
constructor in object oriented concepts.
 This method called when an object is created from the class
and it allow the class to initialize the attributes of a class.
self :
 self represents the instance of the class.
 By using the "self" keyword we can access
the attributes and methods of the class in python.
Example:
Description of previous example:
 "self" represents the same object or instance of the class. If you see, inside the
method "get_area"  we have used "self.length" to get the value of the
attribute "length".  attribute "length" is bind to the object(instance of the class) at the time
of object creation. 
 "self" represents the object inside the class. "self" works just like "r" in the statement  "r =
Rectangle(160, 120, 2000)". 
 If you see the method structure "def get_area(self): "  we have used "self" as a parameter
in the method because whenever we call the method  the object (instance of class)
automatically passes as a first argument along with other arguments of the method.
 If no other arguments are provided only "self" is passed to the method. That's the reason
we use "self" to call the method inside the class("self.get_area()").  we use
object( instance of class) to call the method outside of the class
definition("r.get_area()"). "r" is the instance of the class, when we call
method "r.get_area()"  the instance "r" is passed as first argument in the place of self.
 r = Rectangle(160, 120, 2000)
Note: "r" is the representation of the object outside of the class and "self"  is the
representation of the object inside  the class.
Create a Bookstore class in Python
Output:
Questions
 Create a class named Person, use the __init__() function to assign values for
name and age.
 Create a Cricle class and intialize it with radius. Make two methods getArea
and getCircumference inside this class.
 Create a Temprature class. Make two methods :
1. convertFahrenheit - It will take celsius and will print it into Fahrenheit.
2. convertCelsius - It will take Fahrenheit and will convert it into Celsius.
 Create a Student class and initialize it with name and roll number. Make
methods to :
1. Display - It should display all informations of the student.
2. setAge - It should assign age to student
3. setMarks - It should assign marks to the student.
The self Parameter
 The self parameter is a reference to the current instance of the class,
and is used to access variables that belongs to the class.
 It does not have to be named self , you can call it whatever you like,
but it has to be the first parameter of any function in the class:
Inheritance
 It refers to defining a new class with little or no modification to an
existing class. The new class is called derived (or child) class and the
one from which it inherits is called the base (or parent) class.
 Syntax
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

 Derived class inherits features from the base class, adding new features
to it. This results into re-usability of code.
Example
Multiple Inheritance in Python
 In multiple inheritance, the features of all the base classes are inherited
into the derived class. The syntax for multiple inheritance is similar to
single inheritance.
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
Pass
 Here, MultiDerived is derived from classes Base1 and
 Base2.
Example:
Multilevel inheritance
 In multilevel inheritance, features of the base class and the derived
class is inherited into the new derived class.

class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
Example:
 Polymorphism
 Polymorphism means having many forms. In programming,
polymorphism means same function name (but different signatures)
being uses for different types.
 As we know, a child class inherits all the methods from the parent
class. However, you will encounter situations where the method
inherited from the parent class doesn’t quite fit into the child class. In
such cases, you will have to re-implement method in the child class.
This process is known as Method Overriding.
Polymorphism with Inheritance:
Method Overriding
 Method overriding is an ability of any object-oriented programming language
that allows a subclass or child class to provide a specific implementation of a
method that is already provided by one of its super-classes or parent classes.
 When a method in a subclass has the same name, same parameters or signature
and same return type(or sub-type) as a method in its super-class, then the
method in the subclass is said to override the method in the super-class.
...
Override means having two methods with the same
name but doing different tasks. It means that one of the
methods overrides the other.
If there is any method in the superclass and a method
with the same name in a subclass, then by executing
the method, the method of the corresponding class will
be executed.
Polymorphism with a Function and
objects:
 It is also possible to create a function that can take any object, allowing
for polymorphism. In this example, let’s create a function called
“func()” which will take an object which we will name “obj”.
 Though we are using the name ‘obj’, any instantiated object will be
able to be called into this function. Next, lets give the function
something to do that uses the ‘obj’ object we passed to it.
 In this case lets call the three methods, viz., capital(), language() and
type(), each of which is defined in the two classes ‘India’ and ‘USA’.
Data abstraction in python
Abstraction is an important aspect of object-oriented
programming. In python, we can also perform data
hiding by adding the double underscore (___) as a
prefix to the attribute which is to be hidden. After this,
the attribute will not be visible outside of the class
through the object.
Example:
Access Modifiers in Python : Public,
Private and Protected
 Most programming languages has three forms of access modifiers,
which are Public, Protected and Private in a class.
 Python uses ‘_’ symbol to determine the access control for a specific
data member or a member function of a class. Access specifiers in
Python have an important role to play in securing data from
unauthorized access and in preventing it from being exploited.
 A Class in Python has three types of access modifiers –
 Public Access Modifier
 Protected Access Modifier
 Private Access Modifier
Introduction
Public Access Modifier:
 The members of a class which are declared public are easily accessible
from any part of the program. All data members and member functions of
a class are public by default.
Protected Access Modifier:
 The members of a class which are declared protected are only accessible to
a class derived from it. Data members of a class are declared protected by
adding a single underscore ‘_’ symbol before the data member of that
class.
 Private Access Modifier:
 The members of a class which are declared private are accessible within
the class only, private access modifier is the most secure access modifier.
Data members of a class are declared private by adding a double
underscore ‘__’ symbol before the data member of that class.
Example: public
Example: Protected
Example: Private
Encapsulation
 Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP). 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 type of
variables are known as private variable.
 A class is an example of encapsulation as it encapsulates all the data that is
member functions, variables, etc.
 An objects variables should not always be directly accessible.
 To prevent accidental change, an objects variables can sometimes only be
changed with an objects methods. Those type of variables are private variables.
 The methods can ensure the correct values are set. If an incorrect value is set, the
method can return an error.
 A double underscore: Private variable, harder to access but still possible.
Example
Static Keyword(Class or Static variables )
Class or Static variables are the variables that belong
to the class and not to objects. Class or Static variables
are shared amongst objects of the class.
All variables which are assigned a value in the class
declaration are class variables. And
Variables which are assigned values inside class
methods are instance variables.
Static Methods in Python
Just like static variables, static methods are the methods which are bound to the
class rather than an object of the class and hence are called using the class name
and not the objects of the class.

As static methods are bound to the class hence they cannot change the state of an
object.

To call a static method we don't need any class object it can be directly called using
the class name.

In python there are two ways of defining a static method:


 Using the staticmethod()
 Using the @staticmethod
Define static method using staticmethod()

we declared the info method as static method outside the class using


the staticmethod() function approach and after that we were able to call the info() method
directly using the class Shape.
Define static method using @staticmethod
User-defined Exceptions in Python with Examples
 Python also provides exception handling method with the help of try-
except.
 Some of the standard exceptions which are most frequent include
IndexError, ImportError, IOError, ZeroDivisionError, TypeError and
FileNotFoundError. A user can create his own error using exception
class.
Thanks

You might also like