SlideShare a Scribd company logo
Module-5
Classes and Objects
DEPARTMENT OF MECHANICAL ENGINEERING
MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE
By: Prof.Yogesh Kumar K J
Assistant Professor
Overview
A class in python is the blueprint from which specific objects are created. It lets you structure
your software in a particular way. Here comes a question how? Classes allow us to logically
group our data and function in a way that it is easy to reuse and a way to build upon if need to
be. Consider the below image.
(a) (b)
Overview
In the first image (a), it represents a blueprint of a house that can be considered as Class.
With the same blueprint, we can create several houses and these can be considered
as Objects. Using a class, you can add consistency to your programs so that they can be used
in cleaner and efficient ways. The attributes are data members (class variables and instance
variables) and methods which are accessed via dot notation.
 Class variable is a variable that is shared by all the different objects/instances of a class.
 Instance variables are variables which are unique to each instance. It is defined inside a
method and belongs only to the current instance of a class.
 Methods are also called as functions which are defined in a class and describes the
behaviour of an object.
Overview
Now, let us move ahead and see how it works in Spyder. To get started, first have a look at the
syntax of a python class
Syntax:
class Class_name:
statement-1
.
.
statement-N
Here, the “class” statement creates a new class definition.The name of the class immediately
follows the keyword “class” in python which is followed by a colon.
To create a class in python, consider the below example:
class student:
pass
#no attributes and methods
s_1=student()
s_2=student()
#instance variable can be created manually
s_1.first="yogesh"
s_1.last="kumar"
s_1.email="yogesh@gmail.co"
s_1.age=35
s_2.first="anil"
s_2.last="kumar"
s_2.email="anil@yahoo.com"
s_2.age=36
print(s_1.email)
print(s_2.email)
Output:
yogesh@gmail.co
anil@yahoo.com
Now, what if we don’t want to manually set these variables. You will
see a lot of code and also it is prone to error. So to make it
automatic, we can use “init” method. For that, let’s understand what
exactly are methods and attributes in a python class.
Methods and Attributes in a Python Class
Creating a class is incomplete without some functionality. So functionalities can be defined by
setting various attributes which acts as a container for data and functions related to those
attributes. Functions in python are also called as Methods.
init method, it is a special function which gets called whenever a new object of that class is
instantiated.You can think of it as initialize method or you can consider this as constructors if
you’re coming from any another object-oriented programming background such as C++, Java
etc.
Now when we set a method inside a class, they receive instance automatically.
Let’s go ahead with python class and accept the first name, last name and fees using this
method.
class student:
def __init__(self, first, last, fee):
self.fname=first
self.lname=last
self.fee=fee
self.email=first + "." + last + "@yahoo.com"
s_1=student("yogesh","kumar",75000)
s_2=student("anil","kumar",100000)
print(s_1.email)
print(s_2.email)
print(s_1.fee)
print(s_2.fee)
Output:
yogesh.kumar@yahoo.com
anil.kumar@yahoo.com
75000
100000
“init” method, we have set these instance variables (self, first, last,
fee). Self is the instance which means whenever we write
self.fname=first, it is same as s_1.first=’yogesh’. Then we have
created instances of employee class where we can pass the values
specified in the init method. This method takes the instances as
arguments.
Instead of doing it manually, it will be done automatically now.
Methods and Attributes in a Python Class
Next, we want the ability to perform some kind of action. For that, we will add a method to this class.
Suppose I want the functionality to display the full name of the employee. So let’s us implement this
practically
class student:
def __init__(self, first, last, fee):
self.fname=first
self.lname=last
self.fee=fee
self.email=first + "." + last + "@yahoo.com"
def fullname(self):
return '{}{}'.format(self.fname,self.lname)
s_1=student("yogesh", "kumar", 75000)
s_2=student("anil", "kumar", 100000)
print(s_1.email)
print(s_2.email)
print(s_1.fullname())
print(s_2.fullname())
Output:
yogesh.kumar@yahoo.com
anil.kumar@yahoo.com
yogeshkumar
anilkumar
As you can see above, we have created a method called “full
name” within a class. So each method inside a python class
automatically takes the instance as the first argument. Now within
this method, we have written the logic to print full name and
return this instead of s_1 first name and last name. Next, we have
used “self” so that it will work with all the instances. Therefore to
print this every time, we use a method.
Methods and Attributes in a Python Class
Moving ahead with Python classes, there are variables which are shared among all the instances of a
class. These are called as class variables. Instance variables can be unique for each instance like
names, email, fee etc. Complicated? Let’s understand this with an example. Refer the code below to find
out the annual rise in the fee.
class student:
perc_raise =1.05
def __init__(self, first, last, fee):
self.fname=first
self.lname=last
self.fee=fee
self.email=first + "." + last + "@yahoo.com"
def fullname(self):
return "{}{}".format(self.fname,self.lname)
def apply_raise(self):
self.fee=int(self.fee*1.05)
s_1=student("yogesh","kumar",350000)
s_2=student("anil","kumar",100000)
print(s_1.fee)
s_1.apply_raise()
print(s_1.fee)
Output:
350000
367500
As you can see above, we have printed the fees first and then
applied the 1.5% increase. In order to access these class
variables, we either need to access them through the class or
an instance of the class.
Methods and Attributes in a Python Class
Attributes in a Python Class
Attributes in Python defines a property of an object, element or a file. There are two types of attributes:
Built-in Class Attributes: There are various built-in attributes present inside Python classes. For
example _dict_, _doc_, _name _, etc. Let us take the same example where we want to view all the key-
value pairs of student1. For that, we can simply write the below statement which contains the class
namespace:
print(s_1.__dict__)
After executing it, you will get output such as: {‘fname’:‘yogesh’,‘lname’:‘kumar’,‘fee’: 350000, ’email’:
‘yogesh.kumar@yahoo.com’}
Attributes defined by Users: Attributes are created inside the class definition. We can dynamically
create new attributes for existing instances of a class. Attributes can be bound to class names as well.
Next, we have public, protected and private attributes. Let’s understand them in detail:
Naming Type Meaning
Name Public These attributes can be freely used inside or outside of a class definition
_name Protected
Protected attributes should not be used outside of the class definition, unless
inside of a subclass definition
__name Private
This kind of attribute is inaccessible and invisible. It’s neither possible to read
nor to write those attributes, except inside of the class definition itself
Next, let’s understand the most important component in a python class i.e Objects.
Attributes in a Python Class
What are objects in a Python Class?
As we have discussed above, an object can be
used to access different attributes. It is used to
create an instance of the class. An instance is an
object of a class created at run-time.
To give you a quick overview, an object basically
is everything you see around. For eg: A dog is an
object of the animal class, I am an object of the
human class. Similarly, there can be different
objects to the same phone class. This is quite
similar to a function call which we have already
discussed.
Objects in a Python
class MyClass:
def func(self):
print('Hello')
# create a new MyClass
ob = MyClass()
ob.func()
Programmer-defined types
We have many of Python’s built-in types; now we are going to define a new type. As an example, we will
create a type called Point that represents a point in two-dimensional space.
(0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the
origin. A programmer-defined type is also called a class. A class definition looks like this:
class Point:
"""Represents a point in 2-D space."""
The header indicates that the new class is called Point.The body is a docstring (documentation strings)
that explains what the class is for. Defining a class named Point creates a class object.
>>> Point
<class ' main .Point'>
Because Point is defined at the top level, its “full name” is main .Point.The class object is like a factory
for creating objects.To create a Point, we call Point as if it were a function.
Point
>>> blank = Point()
>>> blank
< main .Point object at 0xb7e9d3ac>
 The return value is a reference to a Point object, which we assign to blank. Creating a new object is
called instantiation, and the object is an instance of the class.
 When we print an instance, Python tells you what class it belongs to and where it is stored in
 memory.
 Every object is an instance of some class, so “object” and “instance” are interchangeable.
 But in this chapter I use “instance” to indicate that I am talking about a programmer defined type.
Attributes
We can assign values to an instance using dot notation:
>>> blank.x = 3.0
>>> blank.y = 4.0
In this case, though, we are assigning values to named elements of an object.These elements are called attributes.
The variable blank refers to a Point object, which contains two attributes. Each attribute refers to a floating-point
number.We can read the value of an attribute using the same syntax:
>>> blank.y
4.0
>>> x = blank.x
>>> x
3.0
The expression blank.x means, “Go to the object blank refers to and get the value of x.” In the example, we
assign that value to a variable named x.
There is no conflict between the variable x and the attribute x.You can use dot notation as part of any expression.
Overview
For example:
>>> '(%g, %g)' % (blank.x, blank.y) '(3.0, 4.0)'
>>> distance = math.sqrt(blank.x**2 + blank.y**2)
>>> distance
5.0
Rectangles
 We are designing a class to represent rectangles.There are at least two possibilities
 You could specify one corner of the rectangle (or the center), the width, and the height
 You could specify two opposing corners. At this point it is hard to say whether either is better than
the other, so we’ll implement the first one, just as an example.
Here is the class definition:
class Rectangle:
"""Represents a rectangle.
attributes: width, height, corner. """
Rectangle
The expression box.corner.x means, “Go to the object box refers to and select the attribute named
corner; then go to that object and select the attribute named x.”
The docstring lists the attributes: width and height are numbers; corner is a Point object that specifies
the lower-left corner.
To represent a rectangle, we have to instantiate a Rectangle object and assign values to the
attributes:
box = Rectangle( )
box.width = 100.0
box.height = 200.0
box.corner = Point( )
box.corner.x = 0.0
box.corner.y = 0.0
An object that is an attribute of another object is embedded.
Overview
Overview
Overview
Overview
Overview
Overview
Ad

More Related Content

Similar to Module-5-Classes and Objects for Python Programming.pptx (20)

Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptxoogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
BhojarajTheking
 
Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
rd1742
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMINGOOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
talha ijaz
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
 
python.pptx
python.pptxpython.pptx
python.pptx
GayathriP95
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
Reflection
ReflectionReflection
Reflection
Piyush Mittal
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
Sasidhar Kothuru
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
Navaneethan Naveen
 
Module IV_updated(old).pdf
Module IV_updated(old).pdfModule IV_updated(old).pdf
Module IV_updated(old).pdf
R.K.College of engg & Tech
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
rumanatasnim415
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptxoogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
BhojarajTheking
 
Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
rd1742
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMINGOOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 

Recently uploaded (20)

最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
W1 WDM_Principle and basics to know.pptx
W1 WDM_Principle and basics to know.pptxW1 WDM_Principle and basics to know.pptx
W1 WDM_Principle and basics to know.pptx
muhhxx51
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
Compiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptxCompiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptx
RushaliDeshmukh2
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Comprehensive-Event-Management-System.pptx
Comprehensive-Event-Management-System.pptxComprehensive-Event-Management-System.pptx
Comprehensive-Event-Management-System.pptx
dd7devdilip
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
New Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdfNew Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdf
mohamedezzat18803
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32
CircuitDigest
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
W1 WDM_Principle and basics to know.pptx
W1 WDM_Principle and basics to know.pptxW1 WDM_Principle and basics to know.pptx
W1 WDM_Principle and basics to know.pptx
muhhxx51
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
Compiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptxCompiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptx
RushaliDeshmukh2
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Comprehensive-Event-Management-System.pptx
Comprehensive-Event-Management-System.pptxComprehensive-Event-Management-System.pptx
Comprehensive-Event-Management-System.pptx
dd7devdilip
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
New Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdfNew Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdf
mohamedezzat18803
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32
CircuitDigest
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
Ad

Module-5-Classes and Objects for Python Programming.pptx

  • 1. Module-5 Classes and Objects DEPARTMENT OF MECHANICAL ENGINEERING MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE By: Prof.Yogesh Kumar K J Assistant Professor
  • 2. Overview A class in python is the blueprint from which specific objects are created. It lets you structure your software in a particular way. Here comes a question how? Classes allow us to logically group our data and function in a way that it is easy to reuse and a way to build upon if need to be. Consider the below image. (a) (b)
  • 3. Overview In the first image (a), it represents a blueprint of a house that can be considered as Class. With the same blueprint, we can create several houses and these can be considered as Objects. Using a class, you can add consistency to your programs so that they can be used in cleaner and efficient ways. The attributes are data members (class variables and instance variables) and methods which are accessed via dot notation.  Class variable is a variable that is shared by all the different objects/instances of a class.  Instance variables are variables which are unique to each instance. It is defined inside a method and belongs only to the current instance of a class.  Methods are also called as functions which are defined in a class and describes the behaviour of an object.
  • 4. Overview Now, let us move ahead and see how it works in Spyder. To get started, first have a look at the syntax of a python class Syntax: class Class_name: statement-1 . . statement-N Here, the “class” statement creates a new class definition.The name of the class immediately follows the keyword “class” in python which is followed by a colon.
  • 5. To create a class in python, consider the below example: class student: pass #no attributes and methods s_1=student() s_2=student() #instance variable can be created manually s_1.first="yogesh" s_1.last="kumar" s_1.email="[email protected]" s_1.age=35 s_2.first="anil" s_2.last="kumar" s_2.email="[email protected]" s_2.age=36 print(s_1.email) print(s_2.email) Output: [email protected] [email protected] Now, what if we don’t want to manually set these variables. You will see a lot of code and also it is prone to error. So to make it automatic, we can use “init” method. For that, let’s understand what exactly are methods and attributes in a python class.
  • 6. Methods and Attributes in a Python Class Creating a class is incomplete without some functionality. So functionalities can be defined by setting various attributes which acts as a container for data and functions related to those attributes. Functions in python are also called as Methods. init method, it is a special function which gets called whenever a new object of that class is instantiated.You can think of it as initialize method or you can consider this as constructors if you’re coming from any another object-oriented programming background such as C++, Java etc. Now when we set a method inside a class, they receive instance automatically. Let’s go ahead with python class and accept the first name, last name and fees using this method.
  • 7. class student: def __init__(self, first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" s_1=student("yogesh","kumar",75000) s_2=student("anil","kumar",100000) print(s_1.email) print(s_2.email) print(s_1.fee) print(s_2.fee) Output: [email protected] [email protected] 75000 100000 “init” method, we have set these instance variables (self, first, last, fee). Self is the instance which means whenever we write self.fname=first, it is same as s_1.first=’yogesh’. Then we have created instances of employee class where we can pass the values specified in the init method. This method takes the instances as arguments. Instead of doing it manually, it will be done automatically now. Methods and Attributes in a Python Class
  • 8. Next, we want the ability to perform some kind of action. For that, we will add a method to this class. Suppose I want the functionality to display the full name of the employee. So let’s us implement this practically class student: def __init__(self, first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" def fullname(self): return '{}{}'.format(self.fname,self.lname) s_1=student("yogesh", "kumar", 75000) s_2=student("anil", "kumar", 100000) print(s_1.email) print(s_2.email) print(s_1.fullname()) print(s_2.fullname()) Output: [email protected] [email protected] yogeshkumar anilkumar As you can see above, we have created a method called “full name” within a class. So each method inside a python class automatically takes the instance as the first argument. Now within this method, we have written the logic to print full name and return this instead of s_1 first name and last name. Next, we have used “self” so that it will work with all the instances. Therefore to print this every time, we use a method. Methods and Attributes in a Python Class
  • 9. Moving ahead with Python classes, there are variables which are shared among all the instances of a class. These are called as class variables. Instance variables can be unique for each instance like names, email, fee etc. Complicated? Let’s understand this with an example. Refer the code below to find out the annual rise in the fee. class student: perc_raise =1.05 def __init__(self, first, last, fee): self.fname=first self.lname=last self.fee=fee self.email=first + "." + last + "@yahoo.com" def fullname(self): return "{}{}".format(self.fname,self.lname) def apply_raise(self): self.fee=int(self.fee*1.05) s_1=student("yogesh","kumar",350000) s_2=student("anil","kumar",100000) print(s_1.fee) s_1.apply_raise() print(s_1.fee) Output: 350000 367500 As you can see above, we have printed the fees first and then applied the 1.5% increase. In order to access these class variables, we either need to access them through the class or an instance of the class. Methods and Attributes in a Python Class
  • 10. Attributes in a Python Class Attributes in Python defines a property of an object, element or a file. There are two types of attributes: Built-in Class Attributes: There are various built-in attributes present inside Python classes. For example _dict_, _doc_, _name _, etc. Let us take the same example where we want to view all the key- value pairs of student1. For that, we can simply write the below statement which contains the class namespace: print(s_1.__dict__) After executing it, you will get output such as: {‘fname’:‘yogesh’,‘lname’:‘kumar’,‘fee’: 350000, ’email’: ‘[email protected]’}
  • 11. Attributes defined by Users: Attributes are created inside the class definition. We can dynamically create new attributes for existing instances of a class. Attributes can be bound to class names as well. Next, we have public, protected and private attributes. Let’s understand them in detail: Naming Type Meaning Name Public These attributes can be freely used inside or outside of a class definition _name Protected Protected attributes should not be used outside of the class definition, unless inside of a subclass definition __name Private This kind of attribute is inaccessible and invisible. It’s neither possible to read nor to write those attributes, except inside of the class definition itself Next, let’s understand the most important component in a python class i.e Objects. Attributes in a Python Class
  • 12. What are objects in a Python Class? As we have discussed above, an object can be used to access different attributes. It is used to create an instance of the class. An instance is an object of a class created at run-time. To give you a quick overview, an object basically is everything you see around. For eg: A dog is an object of the animal class, I am an object of the human class. Similarly, there can be different objects to the same phone class. This is quite similar to a function call which we have already discussed.
  • 13. Objects in a Python class MyClass: def func(self): print('Hello') # create a new MyClass ob = MyClass() ob.func()
  • 14. Programmer-defined types We have many of Python’s built-in types; now we are going to define a new type. As an example, we will create a type called Point that represents a point in two-dimensional space. (0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the origin. A programmer-defined type is also called a class. A class definition looks like this: class Point: """Represents a point in 2-D space.""" The header indicates that the new class is called Point.The body is a docstring (documentation strings) that explains what the class is for. Defining a class named Point creates a class object. >>> Point <class ' main .Point'> Because Point is defined at the top level, its “full name” is main .Point.The class object is like a factory for creating objects.To create a Point, we call Point as if it were a function.
  • 15. Point >>> blank = Point() >>> blank < main .Point object at 0xb7e9d3ac>  The return value is a reference to a Point object, which we assign to blank. Creating a new object is called instantiation, and the object is an instance of the class.  When we print an instance, Python tells you what class it belongs to and where it is stored in  memory.  Every object is an instance of some class, so “object” and “instance” are interchangeable.  But in this chapter I use “instance” to indicate that I am talking about a programmer defined type.
  • 16. Attributes We can assign values to an instance using dot notation: >>> blank.x = 3.0 >>> blank.y = 4.0 In this case, though, we are assigning values to named elements of an object.These elements are called attributes. The variable blank refers to a Point object, which contains two attributes. Each attribute refers to a floating-point number.We can read the value of an attribute using the same syntax: >>> blank.y 4.0 >>> x = blank.x >>> x 3.0 The expression blank.x means, “Go to the object blank refers to and get the value of x.” In the example, we assign that value to a variable named x. There is no conflict between the variable x and the attribute x.You can use dot notation as part of any expression.
  • 17. Overview For example: >>> '(%g, %g)' % (blank.x, blank.y) '(3.0, 4.0)' >>> distance = math.sqrt(blank.x**2 + blank.y**2) >>> distance 5.0
  • 18. Rectangles  We are designing a class to represent rectangles.There are at least two possibilities  You could specify one corner of the rectangle (or the center), the width, and the height  You could specify two opposing corners. At this point it is hard to say whether either is better than the other, so we’ll implement the first one, just as an example. Here is the class definition: class Rectangle: """Represents a rectangle. attributes: width, height, corner. """
  • 19. Rectangle The expression box.corner.x means, “Go to the object box refers to and select the attribute named corner; then go to that object and select the attribute named x.” The docstring lists the attributes: width and height are numbers; corner is a Point object that specifies the lower-left corner. To represent a rectangle, we have to instantiate a Rectangle object and assign values to the attributes: box = Rectangle( ) box.width = 100.0 box.height = 200.0 box.corner = Point( ) box.corner.x = 0.0 box.corner.y = 0.0 An object that is an attribute of another object is embedded.