Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 07 OOPs in Python 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

UNIT

Object Oriented Programming (OOP)


in Python – I

Names of Sub-Units

Introduction, Classes, Inheritance, Overriding Methods, Data Hiding, Classes and Objects, Programmer-
Defined Types, Attributes, Instances as Return Values, Mutable Objects, Copying, Classes and Functions,
Time Class, Pure Functions, Modifiers, Prototyping versus Planning

Overview

This unit begins by discussing about the concept of object-oriented programming. Next, the unit
discusses the classes, inheritance and overriding methods. Further the unit explains the data hiding,
classes and objects, attributes and instances as return values. Towards the end, the unit discusses the
time class and prototyping versus planning.

Learning Objectives

In this unit, you will learn to:


 Discuss the concept of object-oriented programming
 Explain the concept of classes, inheritance and overriding methods
 Describe the classes and objects, attributes and mutable objects
 Explain the significance of copying, time class and pure functions
 Discuss the prototyping versus planning
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

Learning Outcomes

At the end of this unit, you would:


 Evaluate the concept of object-oriented programming
 Assess the concept of classes, inheritance and overriding methods
 Evaluate the classes and objects, attributes and mutable objects
 Determine the significance of copying, time class and pure functions
 Explore the concept of prototyping versus planning

Pre-Unit Preparatory Material

 https://www.cse.iitd.ac.in/~pkalra/csl101/Python-OOP.pdf

7.1 INTRODUCTION
Object-oriented programming (OOP) is a method of organizing a programme by grouping together
similar characteristics and activities into separate objects. Objects are similar to the components of a
system in terms of concept. Consider a programme like a factory assembly line. A system component
processes some material at each step of the assembly line, eventually changing raw material into a
finished product.

Data, such as raw or pre-processed materials at each stage on an assembly line, and behaviour, such
as the action each assembly line component performs, are both contained in an object. Object-oriented
programming (OOP) is a programming paradigm for arranging programmes so that properties and
behaviours are grouped together into individual objects.

An object could, for example, represent a person with attributes such as a name, age, and address, as
well as activities like walking, talking, breathing, and running. It could also represent an email with
features such as a recipient list, topic, and text, as well as actions such as attaching files and sending.

Real Object-oriented programming, or OOP, is a method for modelling physical, real-world objects such
as cars, as well as relationships between objects such as corporations and employees, students and
teachers, and so on. -world entities are modelled as software objects with data and the ability to perform
particular activities in OOP. Another prominent programming paradigm is procedural programming,
which constructs a programme like a recipe by providing a series of stages, such as functions and code
blocks, that flow sequentially to achieve a goal.

The crucial lesson is that objects are at the heart of Python’s object-oriented programming, not only in
terms of expressing data, as in procedural programming, but also in terms of the program’s general
structure.

2
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

7.2 CLASSES
A class is a blueprint or prototype that is defined by the user to create objects. Classes deliver a group of
data and functionality together. A new class introduces a new type of object, allowing for the creation
of new instances of that type. Each instance of a class can have attributes linked to it to keep track of its
status. Class instances can additionally have methods for changing their state (specified by their class).

To comprehend the requirement for creating a class let’s consider the following scenario: you want to
keep track of the number of dogs with various characteristics such as breed and age. The first element
of a list may be the dog’s breed, while the second element could be its age. What if there are 100 different
dogs? How would you know which one is supposed to be which? What if you wanted to give these dogs
other abilities? This lacks organisation, which is precisely why classes are required.

By constructing a class instance, a class establishes a user-defined data structure with its own data
members and member methods that can be fetched and used. A class is similar to the blueprint of an
object.

Some of the important points about the class in python are as follows:
 A class keyword is used to create classes.
 The variables are the attributes that make up a class.
 Attributes are always exposed to the public can be accessed with the dot operator.

Classes vs Instances

User-defined data structures are created using classes. Methods define the behaviours and activities
that an object formed from a class can execute with its data, while classes define methods.

We will design a Dog class to store information about the various features and behaviours that a dog
can exhibit.

A class is a blueprint for defining a concept. It is devoid of any useful information. The Dog class demands
that a dog have a name and an age, but it does not specify the name or age of a specific dog.

An instance is an object that is built from a class and contains real data, whereas a class is the blueprint.
The Dog class instance is no longer a blueprint. Miles, a four-year-old dog, is an example of a real dog with
a name.

To put it another way, a class is similar to a questionnaire or form. An instance is similar to a form that
has been completed with data. Many instances can be formed from a single class, just as many persons
can fill out the same form with their own unique information.

Define a Class

The class keyword appears first in all class definitions, followed by the class name and a colon. Any code
below the class specification that is indented is considered part of the class’s body.

3
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

An example of a Dog class is as follows:


class Dog:
pass
The Dog class’s body is made up of only one statement: the pass keyword. The word pass is frequently
used as a placeholder for where code will eventually go. It allows you to run this code without getting an
exception from Python.

Right now, the Dog class isn’t very fascinating, so let’s spice it up by defining some characteristics that all
Dog instances should have. We can choose from a variety of properties, including name, age, coat
colour, and breed. We’ll just use name and age to make things easy.

Class attributes are used to declare characteristics that should have the same value for all instances of
the class. For properties that differ from one instance to the next, use instance attributes.

7.2.1 Self-Variable
In Python, the self-variable is used to connect the class instance with the instance method. We must
explicitly provide it as the first method argument to access the instance variables and methods. This
variable is only used by instance methods.

Mostly Object-Oriented programming languages allow you to access the current object without explicitly
passing it as a method argument. The “this” keyword in a Java application can be used to access the
current object. In Python, however, we must declare the object instance as a “self” variable.

The term “self-variable” in Python is not a reserved term. However, it is best practice and convention to
refer to the instance by the variable name “self.”

The following python program is used to show an example of self-variable is as follows:


class Dog:
def init (self, Breed):
self.breed = Breed
def Bark(self):
print(f'{self.breed} is Barking.')
d = Dog('German Shepherd')
d.Bark()
The output of given python code is as follows:
German Shepherd is Barking.

7.2.2 Methods
Objects are used in Object-Oriented Programming (drum roll please). These objects are made up of
properties and actions. Furthermore, attributes specify the object’s properties, whereas methods define
the object’s action. Within a class, these methods are defined. These methods are pieces of reusable code
that can be used at any time in the programme.

Python has a number of different types of these techniques. These skills are essential for being an
effective programmer and, as a result, are beneficial to a data science practitioner.

4
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Types of Methods in Python

In Python, there are three essential types of methods are as follows:


 Instance Method
 Class Method
 Static Method

Instance Methods

Instance methods are used to set or receive information about instances (objects), which is why they’re
called instance methods. In a Python class, they are the most common sort of method.

They contain only one default parameter: self, which refers to a class instance. You don’t have to pass that
every time, though. This parameter’s name can be changed, although it’s best to stay to the standard,
which is self.

Unless you tell Python otherwise, any method you create inside a class is an instance method. Let’s have
a look at how to make an instance method:
class My_class:
def instance_method(self):
return "This is an instance method."
To call an instance method, you must first build a class object/instance. You can use this object to access
any of the class’s methods.
obj = My_class()
obj.instance_method()
Python replaces the self-argument with the instance object, obj, when the instance method is called. As
a result, when defining the instance methods, we need provide one default argument. It’s worth noting
that you don’t have to pass self to instance method (). Python takes care of it for you.

Class Methods

The class methods’ purpose is to set or acquire the class’s information (status). That’s why they’re
referred to as class methods. They have no access to or control over individual instance data. Instead
of being connected to their objects, they are bound to the class. There are two key points to remember
regarding class methods:
 In order to define a class method, you must use the @classmethod decorator to indicate that it is a
class method.
 The default parameter for class methods is cls, which refers to the class. It is not required to name the
default parameter “cls.” However, it is always preferable to follow the rules.

Static Methods

The class data is not accessible to static methods. To put it another way, they don’t require access to the
class data. They are self-sufficient and capable of working alone. They can’t retrieve or set the instance or
class state because they’re not tied to any class attribute.

5
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

We may use the @staticmethod decorator to define a static method (just as we did with the @
classmethod decorator). We don’t need to supply any special or default arguments, unlike instance and
class methods. Let’s have a look at how it’s done:
class My_class:
@staticmethod
def static_method():
return "This is a static method."
And that’s it!

It’s worth noting that there is no default parameter in this scenario. So, how do we refer to static methods
now? We can refer to them as: object/instance of the class:
obj = My_class()
obj.static_method()

7.2.3 Constructor Method


Constructors are commonly employed to create new objects. Constructors are responsible for initializing
(assigning values) the data members of a class when an object is formed. The function Object () { [native
code] } is called the init () function in Python, and it is invoked whenever an object is created.

Types of Constructors
There are two types of constructors are as follows:
 Default constructor: For the object creation a constructor is an essential tool. Python constructs a
non-parameterized constructor with an empty body if we don’t define a constructor. This constructor
is called Default Constructor.
 Parameterized constructor: Constructors with parameters are known as parameterized
constructors. The first argument of the parameterized function is a reference to the instance being
created, which is called self, and the remaining arguments are provided by the programmer.

The following python program is used to show an example of default constructors are as follows:
class books:
# default constructor
def init (self):
self.Book_Name= "Python for Managers"
def print_Book_Name(self):
print(self.Book_Name)
# creating object of the class
objects = books ()
objects.print_Book_Name()
The output of given Python code is as follows:
Python for Managers

7.3 INHERITANCE
In Python programming, inheritance refers to the process of creating a new class from an existing one.
We may inherit the properties of an existing class to our new class using the idea of inheritance. The

6
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

current class is referred to as the parent class, while the new derived class is referred to as the child class.
The types of inheritance in Python include hierarchical inheritance, multilevel inheritance, and single and
multiple inheritances.

7.3.1 Advantages of Inheritance


Some of the advantages of inheritance are as follows:
 Code reusability: It increases the reusability of code. We don›t have to rewrite the same code again
and over. We may use inheritance to inherit features from other classes while simultaneously adding
new features to the derived class.
 Reduces the programmers efforts: Programmers don›t have to create the same code or logic every
time. As a result, programmers› efforts are reduced.
 Readability: The program appears more succinct and organized when inheritance ideas are
implemented. This makes it simple to read. As a result, inheritance enhances code readability.

7.3.2 Characteristics of Inheritance


Inheritance is described as a class’s capacity to derive or inherit properties from another class and
utilise them whenever they are needed. Inheritance has the following characteristics:
 It accurately depicts real-world relationships.
 It allows code to be reused. We don’t have to rewrite the same code every time. It also allows us to
extend the functionality of a class without having to change it.
 It is transitive. It means that if class B is inherited by the class A, then all the sub classes of class B will
also be inherited from class A as well.

7.3.3 Types of Inheritance


The number of child and parent classes involved determines the types of inheritance.

In Python, there are five types of inheritance:


 Single level inheritance
 Multilevel inheritance
 Hierarchical inheritance
 Multiple inheritance
 Hybrid inheritance

Single Level Inheritance

Single inheritance allows a derived class to inherit attributes from a single parent class, allowing for
code reuse and new capabilities to be added to existing code.

7
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

Figure 1 shows the single level inheritance:

Figure1: Single Level Inheritance

Creating a single derive class from one base class is called single inheritance. The syntax for single level
inheritance is as shown below:
class class1:
statement(s)
class class2:
statement(s)
The following Python code shows the single level inheritance:
# Python program to demonstrate
# single inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()
The output of the given Python code is as follows:
This function is in parent class.
This function is in child class.

Multilevel Inheritance

Features from the base class and the derived class are passed down to the new derived class in multilevel
inheritance. This is comparable to the bond between a child and his grandfather. The following Python
code shows the multilevel inheritance:

8
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

# Python program to demonstrate


# multilevel inheritance
# Base class
class Grandfather:
def init (self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def init (self, fathername, grandfathername):
self.fathername = fathername
# invoking constructor of Grandfather class
Grandfather. init (self, grandfathername)
# Derived class
class Son(Father):
def init (self,sonname, fathername, grandfathername):
self.sonname = sonname
# invoking constructor of Father class
Father. init (self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()
The output of the given Python code is as follows:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince

Hierarchical Inheritance

Hierarchical inheritance refers to the process of creating several derived classes from a single base
class. We have a parent (base) class and two child (derived) classes in this programme.

The following Python code shows the hierarchical inheritance:


# Python program to demonstrate
# Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")

9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
The output of the given Python code is as follows:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.

Multiple Inheritance

Multiple inheritance is a kind of inheritance in which a class can be derived from multiple base classes. In
multiple inheritance, the derived class inherits all of the features of the base classes. The following Python
code shows the multiple inheritance:
# Python program to demonstrate
# multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
The output of the given Python code is as follows:
Father: RAM
Mother: SITA

10
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Hybrid Inheritance

The occurrence of two or more types of inheritances at same time is known as hybrid inheritance. Figure
2 an example of hybrid inheritance:

Intermediate

Figure 2: Hybrid Inheritance

The following Python code shows the hybrid inheritance:


# Python program to demonstrate
# hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")
# Driver's code
object = Student3()
object.func1()
object.func2()
The output of the given Python code is as follows:
This function is in school.
This function is in student 1.

7.4 OVERRIDING METHODS


Overriding methods (Inheritance) occurs when a method is specified in both the parent and child classes
with the identical parameter and method name. In Python, method overriding is used to improve the
functionality of a method in a child class.

11
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

The following Python code demonstrates the inheritance with override method:
import random
class Robot:
def init (self, name):
self.name = name
self.health_level = random.random()
def say_hi(self):
print("Hi, I am " + self.name)
def needs_a_doctor(self):
if self.health_level < 0.8:
return True
else:
return False
class PhysicianRobot(Robot):
def say_hi(self):
print("Everything will be okay! ")
print(self.name + " takes care of you!")
def heal(self, robo):
robo.health_level = random.uniform(robo.health_level, 1)
print(robo.name + " has been healed by " + self.name + "!")
doc = PhysicianRobot("Dr. Frankenstein")
rob_list = []
for i in range(5):
x = Robot("Marvin" + str(i))
if x.needs_a_doctor():
print("health_level of " + x.name + " before healing: ",
x.health_level)
doc.heal(x)
print("health_level of " + x.name + " after healing: ", x.health_
level)
rob_list.append((x.name, x.health_level))
print(rob_list)
The output of the given Python code is as follows:
health_level of Marvin0 before healing: 0.3069621222537686
Marvin0 has been healed by Dr. Frankenstein!
health_level of Marvin0 after healing: 0.8820824558133344
health_level of Marvin1 before healing: 0.24810380658063824
Marvin1 has been healed by Dr. Frankenstein!
health_level of Marvin1 after healing: 0.8571344837822491
health_level of Marvin2 before healing: 0.7366886350831788
Marvin2 has been healed by Dr. Frankenstein!
health_level of Marvin2 after healing: 0.9729661081287907
health_level of Marvin3 before healing: 0.509136628880188
Marvin3 has been healed by Dr. Frankenstein!
health_level of Marvin3 after healing: 0.723243981252014
[('Marvin0', 0.8820824558133344), ('Marvin1', 0.8571344837822491),
('Marvin2', 0.9729661081287907), ('Marvin3', 0.723243981252014),
('Marvin4', 0.8274221800830426)]

12
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

7.5 DATA HIDING


Data hiding is a term that refers to the hiding of data or information from the user. It’s one of the most
important components of Object-Oriented programming. It contains information about the object, such
as data members and internal work. Data hiding prevents unwanted changes and protects object integrity
by restricting full data entry by class members. By minimising interdependencies between software
needs, data hiding reduces system complexity and increases robustness. Data hiding is also known as
information hiding. It is a procedure of hiding data when we declare data members as private in a class
so that no other class can access them.

Data hiding is defined in the Python document as isolating the user from a component of the programme
implementation. Some of the module’s objects are hidden, invisible, and accessible by the user. The
program’s modules are simple enough to grasp how to use, however the customer has no idea how
the application works. As a result, data concealing provides security while also eliminating reliance. In
Python, data hiding is a strategy for limiting access to specific users within an application.

Python is used in almost every technical field and has a simple syntax and a large library. The _ double
underscore before done prefix is used to hide data in Python. This makes the members of the class
private and separate from the other classes.

The following python program is used to implement data hiding:


class Sol:
PrivateCounter = 0

def sum(self):
self. PrivateCounter += 2
print(self. PrivateCounter)

count = Sol()
count.sum()
count.sum()
print(count._Sol PrivateCounter)
The output of given python code is as follows:
2
4
4
Some of the advantages of data hiding are as follows:
 By hiding sensitive data from the public, it helps to prevent damage or misuse.
 The irrelevant data is detached from the class objects.
 As the fundamental idea of OOP, it isolates objects.
 It improves security against hackers who are unable to access sensitive information.

13
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

Some of the disadvantages of data hiding are as follows:


 It allows programmers to construct complex code to hide sensitive information from common
customers.
 Data hiding removes the coupling between visible and invisible data, which makes the objects work
faster.

7.6 CLASSES AND OBJECTS


The entire OOPS methodology has been derived from a single root concept called object. An object is
anything that really exists in the world and can be distinguished from others. This definition specifies
that everything in this world is an object. For example, a table, a ball, a car, a dog, a person, etc. all
are objects. Then what is not an object? If something does not really exist, then it is not an object. For
example, our thoughts, imagination, plans, ideas, etc. are not objects, because they do not physically exist.

Every object has some behavior. The behavior of an object is represented by attributes and actions.
For example, let’s take a person whose name is Vihan. Vihan is an object because he exists physically.
He has attributes like name, age, gender, etc. These attributes can be represented by variables in our
programming. For example, name is a string type variable, age is an integer type variable.

Similarly, Vihan can perform some actions like talking, walking, eating and sleeping. We may not write
code for such actions in programming, but we can consider calculations and processing of data as
actions. These actions are performed by methods. We should understand that a function written inside
a class is called a method. So, an object contains variables and methods.

It is possible that some objects may have similar behavior. Such objects belong to same category called
a class. For example, not only Vihan, but all the other persons have various common attributes and
actions. So, they are all objects of the same class, Person. Now observe that the Person will not exist
physically but only Vihan, Kamal, Priya, etc. exist physically. This means, a class is a group name and does
not exist physically, but objects exist physically, as shown in Figure 3:

20

Methods
Talk()
Walking Walk()
Eat()

Figure 3: Person Class and Vihan Object

14
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

To understand a class, take a pen and paper and write down all the attributes and actions of any person.
The paper contains the model that depicts a person, so it is called a class. We can find a person with the
name Vihan, who has all the attributes and actions as written on the paper. So, Vihan becomes an object
of the class, Person. This gives a definition for the class. A class is a model or blueprint for creating objects.

We can use a class as a model for creating objects. To write a class, we can write all the characteristics of
objects which should follow the class. These characteristics will guide us to create objects. A class and its
objects are almost the same with the difference that a class does not exist physically, while an object does.
For example, let’s say we want to construct a house. First of all, we will go to an architect who provides
a plan. This plan is only an idea and exists on paper. This is called a class. However, based on this plan, if
we construct the house, it is called an object since it exists physically. So, we can say that we can create
objects from the class. An object does not exist without a class. But a class can exist without any objects.

Let’s take another example. Flower is a class but if we take Rose, Lily, and Jasmine – they are all objects
of flower class. The class flower does not exist physically but its objects, like Rose, Lily and Jasmine exist
physically.

7.6.1 Creating a Class and Object


The class keyword appears first in all class definitions, followed by the class name and a colon. Any code
below the class declaration that is indented is considered part of the class’s body. An example of a Dog
class is as follows:
class Dog:
pass
The Dog class’s body is made up of only one statement: the pass keyword. The word pass is frequently
used as a placeholder for where code will ultimately go. It allows you to run this code without getting an
exception from Python. By convention, Python class names are written in Capitalized Words notation.

Right now, the Dog class isn’t very interesting, so let’s spice it up by defining some attributes that all

Dog objects should have. We may pick from a variety of attributes, including name, age, coat colour, and
breed. We’ll only use name and age to make things easy.

A method called init () defines the characteristics that all Dog objects must have. When a new Dog
object is created, init () assigns the values of the object’s properties to set the object’s initial state.
init (), in other words, creates a new instance of the class.

You can pass any number of parameters to init (), but the first parameter is always a variable namedself.
When a new class instance is generated, it is immediately given to the self-argument in init () sothat new
attributes on the object may be specified.

Let’s add an init () method to the Dog class, which will produce the .name and .age attributes withthe
help of following Python code:
class Dog:
def init (self, name, age):
self.name = name
self.age = age

15
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

The signature of the init () function is indented four spaces. The method’s body has an eight-space
indentation. The importance of this indentation cannot be overstated. It informs Python that the method
init () belongs to the Dog class.
There are two statements that use the self-variable in the body of init (). The descriptions of these
statements are as follows:
 self.name = Creates an attribute with the name ‘name’ and applies the name parameter’s value to it.
 self.age = Creates an attribute with the name ‘age’ and applies the are parameter’s value to it.

Instance attributes are attributes produced in init (). The value of an instance attribute is uniqueto
each instance of the class. Although all Dog objects have a name and an age, the name and age properties’
values differ based on the Dog instance.
Class attributes, on the other hand, are attributes that have the same value across all class instances.
Outside of init (), you may define a class attribute by setting a value to a variable name.
The Dog class, for example, contains a class property named species that has the value “Canis familiaris”:
class Dog:
# Class attribute
species = "Canis familiaris"
def init (self, name, age):
self.name = name
self.age = age
Class characteristics are defined exactly under the first line of the class name, indented by four spaces.
Class attributes are used to declare characteristics that should have the same value for all instances of
the class. For properties that differ from one instance to the next, use instance attributes.

7.6.2 Instantiate an Object in Python


Open IDLE’s interactive window and type the following:
>>> class dog():
pass:
This creates a new Dog class with no attributes or methods.
Instantiating an object is the process of creating a new object from a class. By entering the class name,
followed by opening and closing parenthesis, you may create a new Dog object:
>>> Dog()
< main .Dog object at 0x106702d30>
At 0x106702d30, you now have a new Dog object. 0x106702d30 is a memory address where the Dog
object is stored in your computer system. It’s important to note that the address displayed on your screen
will be different.

Create a second Dog object as follows:


>>> Dog()
< main .Dog object at 0x0004ccc90>
The memory address of the new Dog instance is different. That’s because it’s a whole new instance, fully
different from the original Dog object you created.

16
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Type the following to see it in a different way:


>>> a = Dog()
>>> b = Dog()
>>> a == b
False
You create two new Dog objects in this code and assign them to the variables a and b. When you use

the == operator to compare a and b, the outcome is False. Despite the fact that a and b are both Dog
instances, they represent two different things in memory.

The following python code shows the way to create class and its object:
#Defining a class and creating its objects
class Person(): #class
def input_details(self): #function
self.name = input("Enter your name:")
self.age = input("Enter your age:")
def Print_details(self): #2nd function
print("Name:",self.name)
print("Age:",self.age)
p = Person() # object of the above class
p.input_details() #calling the function using the class object.
p.Print_details() #calling the 2nd function using the class object.
The output of the given Python code is as follows:
Enter your name: Ram
Enter your age: 25
Name: Ram
Age: 25

7.7 PROGRAMMER-DEFINED TYPES


A class is another name for a programmer-defined type. The following is an example of a class definition:
“””Represents a point in two-dimensional space.””” The new class is called Point, according to the header.

The following python program is used to implement programmer-defined types:


class File:
"""Represents a computer file."""
...

print(type(str))
print (type (File))
print(type("Pooja"))
print (type (File ()))
The output of given python code is as follows:
<class 'type'>
<class 'type'>
<class 'str'>
<class ' main .File'>

17
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

7.8 ATTRIBUTES
A class’s attributes are function objects that define the methods that its instances should use. They’re
utilised to implement class-level access controls.

The various built-in methods and functions can be used to access a class’s attributes:
 getattr(): This function is used to get at an object’s attribute.
 hasattr(): This function is used to determine whether or not an attribute exists.
 setattr(): The setattr() function is used to change the value of an attribute. If the attribute doesn’t
already exist, it will be created.
 delattr(): Deleting an attribute with this function. If you try to access the attribute after it’s been
deleted, you’ll get the error “class has no attribute.”

The following python program is used to implement the in-built methods of attributes:
# Python code for accessing attributes of class
class Employee:
Name='Radha Yadav'
Salary='30,000'
def show(self):
print (self.Name)
print (self.Salary)
E1 = Employee()
print (getattr(E1,'Name'))

print (hasattr(E1,'Name'))

# sets an attribute
setattr(E1,'height',154)

print (getattr(E1,'height'))

# Remove the attribute


delattr(Employee,'Salary')
The output of given python code is as follows:
Radha Yadav
True
154

7.9 INSTANCES AS RETURN VALUES


An instance is just a case or occurrence of something. This might be an element, document type, or
document that adheres to a certain data type specification in computer technology (DTD).

An instance is a type of object that belongs to a certain class. Instances of a class have the same set of
characteristics, but the contents of those attributes may differ across them.

18
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

A school class, for example, has the following attributes: school Name, school Location, no Of Students,
and School Board. These characteristics are exclusive to the school class and apply to all instances of
the class. Consider the following two examples of school classes. For the previously given qualities, let the
first case contain the values Thames Valley School, London, 355, and St. Thomas Board, respectively,
while the second instance includes the values Cambridge Public School, West Hampshire, 200, and
Cambridge Board, respectively. The two examples are unique and exist independently of one another.
The core structure of the class, however, remains unchanged.

Objects can be returned via functions and methods. This is nothing new, because everything in Python
is an object, and we’ve been returning values for a long time. The distinction here is because we want the
method to use the function Object () { [native code] } to build an object and then return it as the method’s
value. Assume you have a point object and want to discover the midway point between it and another
target point. We want to create a halfway method that accepts another Point as a parameterand
returns the Point that is halfway between the point and the target.

7.10 MUTABLE OBJECTS


The term “mutable” refers to items that can change after being created. We can alter mutable objects
using a variety of methods and functions. The original objects are modified when certain methods and
functions are used. The memory where the changeable objects are kept remains unchanged while any
modifications are made to them.

Mutable is a fancy way of indicating that the object’s internal state has been changed/mutated. So, the
most basic definition is: a mutable object is one whose internal state may be altered. Immutable, on the
other hand, does not allow any changes to the object after it has been formed.

Both of these states are necessary for Python’s data structure to function. If you want to learn more about
the whole Python Data Structure, try this online course that covers many data structures in Python,
including the immutable tuple data structure. You will also obtain a certificate upon completion,which
will undoubtedly increase the value of your portfolio.

When there is no possibility of change across time, it is said to be immutable. In Python, an object is said to
be immutable if its value cannot be altered over time. The value of these items is fixed once they are created.

7.10.1 Objects in Python


Python treats everything as an object. Everything possesses the following three characteristics:
 Identity: This is the address in the computer’s memory to which the item relates.
 Type: This relates to the type of item generated. For instance, number, list, string, and so on.
 Value: This is the value that the object has saved. List=[1,2,3] would, for example, store the numbers
1, 2, and 3.

Some of the examples of mutable objects in python are as follows:


 List
 Dictionary
 Set

19
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

7.11 COPYING
Assignment statements in Python should not copy objects; instead, they form bindings between a target
and an object. When we use the = operator, the user may believe that we are creating a new object;
however, this is not the case. It just introduces a new variable that shares the old object’s reference. When
a user needs to interact with mutable things, he or she looks for a mechanism to make “actual copies” or
“clones” of those objects. Alternatively, a user may want copies of things that they can alter without
modifying the original at the same time; in this case, we generate copies of objects.
A copy is often required so that one copy can be changed without affecting the other. There are two ways
to make copies in Python:
 Shallow copy
 Deep copy

7.11.1 Deep Copy


The term “deep copy” refers to a recursive copying procedure. It entails first creating a new collection
object, then recursively populating it with copies of the original’s child objects. A copy of an object is
copied into another object in a deep copy. Any modifications made to a duplicate of an object are not
reflected in the original object. This is done in Python with the “deepcopy()” method.
The following python program is used to implement deep copy:
# Python code to demonstrate copy operations
import copy

List1 = [10, 12, [33,15], 5]

# using deep copy


List2 = copy.deepcopy(List1)

print ("The original elements before deep copying: ")


for i in range(0,len(List1)):
print (List1[i],end=" ")

print("\r")

# adding and element to new list


List2[2][1] = 5

# Change is reflected in l2
print ("The new list of elements after deep copying: ")
for i in range(0,len( List1)):
print (List2[i],end=" ")

print("\r")
print ("The original elements after deep copying: ")
for i in range(0,len( List1)):
print (List1[i],end=" ")

20
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

The output of given python code is as follows:


The original elements before deep copying:
10 12 [33, 15] 5

The new list of elements after deep copying:


10 12 [33, 5] 5

The original elements after deep copying:

10 12 [33, 15] 5

7.11.2 Shallow Copy


A shallow copy is created by creating a new collection object and then populating it with references
to the original’s child objects. Because the copying operation does not recurse, no copies of the child
objects are created. In a shallow copy, an object’s reference is transferred into another object. Any
modifications made to a duplicate of an object are reflected in the original object. This is done in Python
with the “copy()” method.

The following python program is used to implement shallow copy:


# Python code to demonstrate copy operations
import copy
List1 = [23, 52, [10,15], 44]
List2 = copy.copy(List1)

print ("The original elements before shallow copying: ")


for i in range(0,len(List1)):
print (List1[i],end=" ")
print("\r")
List2[2][0] = 7
print ("The original elements after shallow copying: ")
for i in range(0,len( List1)):
print (List1[i],end=" ")
The output of given python code is as follows:
The original elements before shallow copying:
23 52 [10, 15] 44
The original elements after shallow copying:
23 52 [7, 15] 44 >

7.12 CLASSES AND FUNCTIONS


There is a significant distinction between a class and a function, which is present in all Object-Oriented
Programming Languages. So, even in tiny applications, there is a difference, and Python’s ability to include
the Class is highly useful in larger projects.

A-Class can be described literally as a group or category of entities that share some trait or attribute
and are distinguished from others by sort, kind, or quality (copied from google definitions :P). So, in

21
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

general, a class is an encapsulation of data under a single entity, and the data can be variables (called
attributes) or functions (called methods), and YES, a function can be included in a class, but a class
cannot be a component of a function. Generally, when we construct classes, we call the class or the
functions (methods) included within it using an Object. A class is essentially an Object definition. A
function, on the other hand, is simply a piece of code.

The following python program is used to implement class:


#!/usr/bin/python

class Employee:
'Common base class for all employees'
empCount = 0

def init (self, Name, Salary):


self.Name = Name
self.Salary = Salary
Employee.empCount += 1

def displayCount(self):
print ("Total Employee %d" % Employee.empCount)

def displayEmployee(self):
print ("Name : ", self.Name, ", Salary: ", self.Salary)

Emp1 = Employee("Yogita", 50000)


Emp2 = Employee("Sanjay", 60000)
Emp1.displayEmployee()
Emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
The output of given python code is as follows:
Name : Yogita , Salary: 50000
Name : Sanjay , Salary: 60000
Total Employee 2
As you can see, an Object is essentially all of the data contained under a single identifier, in this instance
Emp1 and Emp2. A class can contain as many objects as it wants, but the architecture of these things
remains constant. This level of efficiency and efficacy cannot be attained only via function. Classes are
a component of the Object-Oriented Programming idea, which is a critical and fundamental notion in
modern programming and a must-have for any successful programmer.

7.13 TIME CLASS


The local time of the day is represented by the time class, which is independent of any given day. The
tzinfo object, which represents the timezone of the supplied time, can be used in this class. The time object
is the naïve object if the tzinfo is none, else it is the aware object.

22
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

The following python program is used to implement time class:


# Implementation of time class
from datetime import time
# calling the constructor
My_time = time(21, 12, 26)
print("Entered time", My_time)
My_time = time(minute = 21)
print("\nTime with one argument", My_time)

My_time = time()
print("\nTime without argument", My_time)
The output of given python code is as follows:
Entered time 21:12:26

Time with one argument 00:21:00

Time without argument 00:00:00

7.13.1 Attributes of Time Class


The attributes of time class is shown in Table 1:

Table 1: Attributes of Time Class

Name of Attributes Description


Min The minimum representation of time possible
Max The maximum representation of time possible
Resolution The smallest time difference possible between two items
Hour The hour range must be between 0 and 24 (not including 24)
Minute Minutes must be in the range of 0 to 60 (not including 60)
Second The second range must be between 0 and 60. (not including 60)
Microsecond Microseconds must be in th e range of 0 to 1000000 (not including 1000000)
Tzinfo Timezone information is stored in this item.
Fold Indicates whether or not the fold occurred during the time period

7.14 PURE FUNCTIONS


A pure function is one whose output value is determined completely by its input values, with no discernible
side effects. A program in functional programming is made up solely of the evaluation of pure functions.
The computation is carried out by a nested or composing function call, with no modifications to state
or mutable data.

The functional programming paradigm is widely used because it has various advantages over other
programming paradigms.

23
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

The following is functional code:


 High level: At a high level, you’re defining the desired outcome rather than specifically detailing the
procedures necessary to achieve it. Single statements are usually brief yet powerful.
 Transparent: A pure function’s behavior is determined only by its inputs and outputs, with no
intermediate values. This reduces the risk of side effects, making debugging easier.
 Parallelizable: Routines that do not create side effects can execute in parallel more readily.

Many programming languages provide some level of functional programming functionality. Almostall
code in some languages adheres to the functional paradigm. One such example is Haskell. Python,on
the other hand, supports functional programming while also incorporating elements from other
programming models.

While an in-depth description of functional programming is quite complicated, the purpose here is not to
offer a precise definition, but to show you what functional programming in Python can achieve.

7.15 MODIFIERS
Access modifiers are used in most object-oriented languages to restrict access to a class’s variables
and functions. The majority of languages employ three sorts of access modifiers: private, public, and
protected.
Access to variables or functions in Python can be regulated using access modifiers, just as in any other
object-oriented programming language. To express the access modifier for a specific data member and
member function in a class, Python uses underscores.
Access modifiers play a crucial role in preventing unwanted access to data as well as preventing it
from being modified. When inheritance is used, there is a significant chance that data will be lost
(manipulated) as a result of undesirable data being sent from the parent class to the child class. As a
result, it is critical to offer the appropriate access modifiers for various data members and member
functions based on the needs.

7.15.1 Types of Modifiers in Python


There are three different types of access modifiers for a class in Python. These access modifiers control
how members of a class can be accessed. Any member of a class can, of course, be accessed from any
member function of the same class. Moving on to the various kinds of access modifiers are as follows:
 Public modifier: The members marked as Public are available from outside the Class through a
class object.
 Protected modifier: Protected members are available from outside the class, but only in a class
derived from it, that is a child or subclass.
 Private modifier: These members can only be accessed from inside the class. There is no outside
access permitted.

7.16 PROTOTYPING VERSUS PLANNING


The development strategy I’m presenting is known as “prototype and patch.” I created a prototype for
each function that did the fundamental computation and then tested it, fixing bugs along the way.

24
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

This method can be useful, especially if you don’t yet have a thorough knowledge of the situation.
However, incremental fixes might result in code that is both too complicated (because it deals with
so many particular instances) and unreliable (since it is difficult to tell if you have detected all of the
problems).

The planned development is an alternative in which high-level knowledge of the problem may make
programming considerably easier. The breakthrough in this situation is that a Time object is really a
three-digit number in base 60 (seehttp://en.wikipedia.org/wiki/Sexagesimal.)! The second attribute is
known as the “one’s column,” the minute attribute is known as the “sixties column,” and your attribute
is known as the “thirty-six hundreds column.”

We were basically conducting addition in base 60 when we wrote add timeandincrement, which is why
we had to carry from one column to the next.

This discovery indicates another way to the problem: we can transform Time objects to integers and take
advantage of the computer’s ability to do integer arithmetic.

Conclusion 7.17 CONCLUSION

 Object-oriented programming (OOP) is a method of organizing a programme by grouping together


similar characteristics and activities into separate objects.
 A class is a blueprint or prototype that is defined by the user to create objects.
 An instance is an object that is built from a class and contains real data, whereas a class is the
blueprint.
 Instance methods are used to set or receive information about instances (objects), which is why
they’re called instance methods.
 The class methods’ purpose is to set or acquire the class’s information (status).
 Constructors are responsible for initializing (assigning values) the data members of a class when
an object is formed.
 In Python programming, inheritance refers to the process of creating a new class from an existing
one.
 Overriding methods (Inheritance) occurs when a method is specified in both the parent and child
classes with the identical parameter and method name.
 Data hiding is a term that refers to the hiding of data or information from the user.
 The entire OOPS methodology has been derived from a single root concept called object.
 An instance is a type of object that belongs to a certain class.
 The term “mutable” refers to items that can change after being created.
 The term “deep copy” refers to a recursive copying procedure.
 A shallow copy is created by creating a new collection object and then populating it with references
to the original’s child objects.
 Access modifiers are used in most object-oriented languages to restrict access to a class’s variables
and functions.

25
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python

7.18 GLOSSARy

 Object-Oriented Programming (OOP): A method of organizing a programme by grouping together


similar characteristics and activities into separate objects.
 Class: A blueprint or prototype that is defined by the user to create objects.
 Instance: An object that is built from a class and contains real data, whereas a class is the blueprint.
 Constructors: The data members of a class when an object is formed.
 Inheritance: The process of creating a new class from an existing one.
 Overriding methods: A method is specified in both the parent and child classes with the identical
parameter and method name.
 Data hiding: A term that refers to the hiding of data or information from the user.
 Object: The entire OOPS methodology has been derived from a single root concept.
 Mutable: It refers to items that can change after being created.
 Deep copy: A recursive copying procedure.
 Shallow copy: It is created by creating a new collection object and then populating it with references
to the original’s child objects.
 Modifiers: An object-oriented language to restrict access to a class’s variables and functions.

7.19 SELF-ASSESSMENT QUESTIONS

A. Essay Type Questions


1. Object-oriented programming (OOP) is a programming paradigm for arranging programmes so
that properties and behaviours are grouped together into individual objects. Describe the concept
of object-oriented programming.
2. A new class introduces a new type of object, allowing for the creation of new instances of that type.
Explain the significance of class in python.
3. The term “self-variable” in Python is not a reserved term. Discuss
4. Evaluate the concept of inheritance with its types.
5. Constructors are commonly employed to create new objects. Explain the concept of constructors.

7.20 ANSWERS AND HINTS FOR SELF-ASSESSMENT QUESTIONS

A. Hints for Essay Type Questions


1. Object-oriented programming (OOP) is a method of organizing a programme by grouping together
similar characteristics and activities into separate objects. Refer to Section Introduction
2. A class is a blueprint or prototype that is defined by the user to create objects. Refer to Section
Classes
26
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

3. In Python, the self-variable is used to connect the class instance with the instance method. Refer to
Section Classes
4. In Python programming, inheritance refers to the process of creating a new class from an existing
one. Refer to Section Inheritance
5. Constructors are responsible for initializing (assigning values) the data members of a class when an
object is formed. Refer to Section Classes

@ 7.21 POST-UNIT READING MATERIAL

 https://www.tutorialspoint.com/object_oriented_python/object_oriented_python_tutorial.pdf
 https://quick-adviser.com/does-python-have-access-modifiers/

7.22 TOPICS FOR DISCUSSION FORUMS

 Discuss with your friends and classmates about the concept of object-oriented programming. Also,
discuss the importance of methods and class in python.

27

You might also like