Unit 07 OOPs in Python 1
Unit 07 OOPs in Python 1
Unit 07 OOPs in Python 1
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
Learning Outcomes
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
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.”
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
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()
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.
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
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
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.
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
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
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.
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
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()
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.
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.
16
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
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
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'))
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.
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.
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
print("\r")
# 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
10 12 [33, 15] 5
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.
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.Name, ", Salary: ", self.Salary)
22
UNIT 07: Object Oriented Programming (OOP) in Python – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
My_time = time()
print("\nTime without argument", My_time)
The output of given python code is as follows:
Entered time 21:12:26
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
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.
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.
25
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Application Development using Python
7.18 GLOSSARy
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
https://www.tutorialspoint.com/object_oriented_python/object_oriented_python_tutorial.pdf
https://quick-adviser.com/does-python-have-access-modifiers/
Discuss with your friends and classmates about the concept of object-oriented programming. Also,
discuss the importance of methods and class in python.
27