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

Recommended

IPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptx
DhavalaShreeBJain
 
Introduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Object Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Unit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
what is class in C++ and classes_objects.ppt
what is class in C++ and classes_objects.ppt
malikliyaqathusain
 
Python3
Python3
Ruchika Sinha
 
My Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 
Presentation on Classes In Python Programming language
Presentation on Classes In Python Programming language
AsadKhokhar14
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
santoshkumar811204
 
مقدمة بايثون .pptx
مقدمة بايثون .pptx
AlmutasemBillahAlwas
 
Class_and_Object_with_Example_Python.pptx janbsbznnsbxghzbbshvxnxhnwn
Class_and_Object_with_Example_Python.pptx janbsbznnsbxghzbbshvxnxhnwn
bandiranvitha
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - Classes
Chariza Pladin
 
Object oriented Programming in Python.pptx
Object oriented Programming in Python.pptx
SHAIKIRFAN715544
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Class, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Object oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Python programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Class
Class
baabtra.com - No. 1 supplier of quality freshers
 
Python advance
Python advance
Mukul Kirti Verma
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 

More Related Content

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

Unit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
what is class in C++ and classes_objects.ppt
what is class in C++ and classes_objects.ppt
malikliyaqathusain
 
Python3
Python3
Ruchika Sinha
 
My Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 
Presentation on Classes In Python Programming language
Presentation on Classes In Python Programming language
AsadKhokhar14
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
santoshkumar811204
 
مقدمة بايثون .pptx
مقدمة بايثون .pptx
AlmutasemBillahAlwas
 
Class_and_Object_with_Example_Python.pptx janbsbznnsbxghzbbshvxnxhnwn
Class_and_Object_with_Example_Python.pptx janbsbznnsbxghzbbshvxnxhnwn
bandiranvitha
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - Classes
Chariza Pladin
 
Object oriented Programming in Python.pptx
Object oriented Programming in Python.pptx
SHAIKIRFAN715544
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Class, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Object oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Python programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Class
Class
baabtra.com - No. 1 supplier of quality freshers
 
Python advance
Python advance
Mukul Kirti Verma
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
what is class in C++ and classes_objects.ppt
what is class in C++ and classes_objects.ppt
malikliyaqathusain
 
My Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 
Presentation on Classes In Python Programming language
Presentation on Classes In Python Programming language
AsadKhokhar14
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
santoshkumar811204
 
Class_and_Object_with_Example_Python.pptx janbsbznnsbxghzbbshvxnxhnwn
Class_and_Object_with_Example_Python.pptx janbsbznnsbxghzbbshvxnxhnwn
bandiranvitha
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - Classes
Chariza Pladin
 
Object oriented Programming in Python.pptx
Object oriented Programming in Python.pptx
SHAIKIRFAN715544
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Class, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Object oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 

Recently uploaded (20)

OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
Microwatt: Open Tiny Core, Big Possibilities
Microwatt: Open Tiny Core, Big Possibilities
IBM
 
Complete guidance book of Asp.Net Web API
Complete guidance book of Asp.Net Web API
Shabista Imam
 
machine learning is a advance technology
machine learning is a advance technology
ynancy893
 
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
resming1
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
Stay Safe Women Security Android App Project Report.pdf
Stay Safe Women Security Android App Project Report.pdf
Kamal Acharya
 
A Cluster-Based Trusted Secure Multipath Routing Protocol for Mobile Ad Hoc N...
A Cluster-Based Trusted Secure Multipath Routing Protocol for Mobile Ad Hoc N...
IJCNCJournal
 
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
KhadijaKhadijaAouadi
 
Structured Programming with C++ :: Kjell Backman
Structured Programming with C++ :: Kjell Backman
Shabista Imam
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
Quiz on EV , made fun and progressive !!!
Quiz on EV , made fun and progressive !!!
JaishreeAsokanEEE
 
20CE404-Soil Mechanics - Slide Share PPT
20CE404-Soil Mechanics - Slide Share PPT
saravananr808639
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
Microwatt: Open Tiny Core, Big Possibilities
Microwatt: Open Tiny Core, Big Possibilities
IBM
 
Complete guidance book of Asp.Net Web API
Complete guidance book of Asp.Net Web API
Shabista Imam
 
machine learning is a advance technology
machine learning is a advance technology
ynancy893
 
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
resming1
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
Stay Safe Women Security Android App Project Report.pdf
Stay Safe Women Security Android App Project Report.pdf
Kamal Acharya
 
A Cluster-Based Trusted Secure Multipath Routing Protocol for Mobile Ad Hoc N...
A Cluster-Based Trusted Secure Multipath Routing Protocol for Mobile Ad Hoc N...
IJCNCJournal
 
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
KhadijaKhadijaAouadi
 
Structured Programming with C++ :: Kjell Backman
Structured Programming with C++ :: Kjell Backman
Shabista Imam
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
Quiz on EV , made fun and progressive !!!
Quiz on EV , made fun and progressive !!!
JaishreeAsokanEEE
 
20CE404-Soil Mechanics - Slide Share PPT
20CE404-Soil Mechanics - Slide Share PPT
saravananr808639
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
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.