SlideShare uma empresa Scribd logo
1 de 14
OOPs CONCEPT IN PYTHON
SANTOSH VERMA
Faculty Development Program: Python Programming
JK Lakshmipat University, Jaipur
(3-7, June 2019)
Important Note
 Please remember that Python completely works on
indentation.
 Use the tab key to provide indentation to your code.
Classes and Objects
Classes
Just like every other Object Oriented Programming language
Python supports classes. Let’s look at some points on Python
classes. Classes are created by keyword class.
 Attributes are the variables that belong to class.
 Attributes are always public and can be accessed using dot (.)
operator. Eg.: Myclass.Myattribute
# A simple example class
class Test:
# A sample method
def fun(self):
print("Hello")
# Driver code
obj = Test()
obj.fun()
Output: Hello
The self
 Class methods must have an extra first parameter in method definition.
do not give a value for this parameter when we call the method, Python
provides it.
 If we have a method which takes no arguments, then we still have to
one argument – the self. See fun() in above simple example.
 This is similar to this pointer in C++ and this reference in Java.
 When we call a method of this object as myobject.method(arg1, arg2),
is automatically converted by Python into MyClass.method(myobject,
arg2) – this is all the special self is about.
# creates a class named MyClass
class MyClass:
# assign the values to the MyClass attributes
number = 0
name = "noname"
def Main():
# Creating an object of the MyClass.Here, 'me' is the object
me = MyClass()
# Accessing the attributes of MyClass, using the dot(.) operator
me.number = 310
me.name = "Santosh"
# str is an build-in function that, creates an string
print(me.name + " " + str(me.number))
# telling python that there is main in the program.
if __name__=='__main__':
Main()
Output: Santosh 310
 The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as
soon as an object of a class is instantiated. The method is useful to do any
initialization you want to do with your object.
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person(‘Santosh')
p.say_hi()
Methods
 Method is a bunch of code that is intended to perform a
particular task in your Python’s code.
 Function that belongs to a class is called an Method.
 All methods require ‘self’ first parameter. If you have coded in
other OOP language you can think of ‘self’ as the ‘this’ keyword
which is used for the current object. It unhides the current
instance variable. ’self’ mostly work like ‘this’.
 ‘def’ keyword is used to create a new method.
class Vector2D:
x = 0.0
y = 0.0
# Creating a method named Set
def Set(self, x, y):
self.x = x
self.y = y
def Main():
# vec is an object of class Vector2D
vec = Vector2D()
# Passing values to the function Set
# by using dot(.) operator.
vec.Set(5, 6)
print("X: " + vec.x + ", Y: " + vec.y)
if __name__=='__main__':
Main()
Output: X: 5, Y: 6
Python In-built class functions
Inheritance
 Inheritance is the capability of one class to derive or inherit the properties
from some another class. The benefits of inheritance are:
 It represents real-world relationships well.
 It provides reusability of a code. We don’t have to write the same code again
and again. Also, it allows us to add more features to a class without modifying
it.
 It is transitive in nature, which means that if class B inherits from another class
A, then all the subclasses of B would automatically inherit from class A.
 Inheritance is defined as a way in which a particular class inherits
features from its base class.
 Base class is also knows as ‘Superclass’ and the class which inherits from
the Superclass is knows as ‘Subclass’
 # Syntax for inheritance
 class derived-classname(superclass-name)
class Person(object): # class Person: of Python 3.x is same as defined here.
def __init__(self, name): # Constructor
self.name = name
def getName(self): # To get name
return self.name
def isEmployee(self): # To check if this person is employee
return False
# Inherited or Sub class (Note Person in bracket)
class Employee(Person):
def isEmployee(self): # Here we return true
return True
# Driver code
emp = Person(“Ram") # An Object of Person
print(emp.getName(), emp.isEmployee())
emp = Employee(“Shyam") # An Object of Employee
print(emp.getName(), emp.isEmployee())
OUTPUT:
Ram False
Shyam True
Explore more on Inheritance Type
Thank You!

Mais conteúdo relacionado

Mais procurados

CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONLalitkumar_98
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Operator Overloading In Python
Operator Overloading In PythonOperator Overloading In Python
Operator Overloading In PythonSimplilearn
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python Home
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptxAkshayAggarwal79
 

Mais procurados (20)

Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Types of methods in python
Types of methods in pythonTypes of methods in python
Types of methods in python
 
Python Modules
Python ModulesPython Modules
Python Modules
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
 
Operator Overloading In Python
Operator Overloading In PythonOperator Overloading In Python
Operator Overloading In Python
 
Python-Polymorphism.pptx
Python-Polymorphism.pptxPython-Polymorphism.pptx
Python-Polymorphism.pptx
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 

Semelhante a Class, object and inheritance in python

Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
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.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2Ahmad Hussein
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineeringIRAH34
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
 
Python Classes and Objects part13
Python Classes and Objects  part13Python Classes and Objects  part13
Python Classes and Objects part13Vishal Dutt
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 

Semelhante a Class, object and inheritance in python (20)

Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
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
 
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
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
 
Python inheritance
Python inheritancePython inheritance
Python inheritance
 
OOPS.pptx
OOPS.pptxOOPS.pptx
OOPS.pptx
 
Python3
Python3Python3
Python3
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Python Classes and Objects part13
Python Classes and Objects  part13Python Classes and Objects  part13
Python Classes and Objects part13
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
Pythonclass
PythonclassPythonclass
Pythonclass
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Only oop
Only oopOnly oop
Only oop
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 

Mais de Santosh Verma

Migrating localhost to server
Migrating localhost to serverMigrating localhost to server
Migrating localhost to serverSantosh Verma
 
Sorting tech comparision
Sorting tech comparisionSorting tech comparision
Sorting tech comparisionSantosh Verma
 
Access modifiers in Python
Access modifiers in PythonAccess modifiers in Python
Access modifiers in PythonSantosh Verma
 
Embedded system design using arduino
Embedded system design using arduinoEmbedded system design using arduino
Embedded system design using arduinoSantosh Verma
 
Snapdragon SoC and ARMv7 Architecture
Snapdragon SoC and ARMv7 ArchitectureSnapdragon SoC and ARMv7 Architecture
Snapdragon SoC and ARMv7 ArchitectureSantosh Verma
 
Trends and innovations in Embedded System Education
Trends and innovations in Embedded System EducationTrends and innovations in Embedded System Education
Trends and innovations in Embedded System EducationSantosh Verma
 

Mais de Santosh Verma (9)

Migrating localhost to server
Migrating localhost to serverMigrating localhost to server
Migrating localhost to server
 
Wordpress tutorial
Wordpress tutorialWordpress tutorial
Wordpress tutorial
 
Sorting tech comparision
Sorting tech comparisionSorting tech comparision
Sorting tech comparision
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Access modifiers in Python
Access modifiers in PythonAccess modifiers in Python
Access modifiers in Python
 
SoC: System On Chip
SoC: System On ChipSoC: System On Chip
SoC: System On Chip
 
Embedded system design using arduino
Embedded system design using arduinoEmbedded system design using arduino
Embedded system design using arduino
 
Snapdragon SoC and ARMv7 Architecture
Snapdragon SoC and ARMv7 ArchitectureSnapdragon SoC and ARMv7 Architecture
Snapdragon SoC and ARMv7 Architecture
 
Trends and innovations in Embedded System Education
Trends and innovations in Embedded System EducationTrends and innovations in Embedded System Education
Trends and innovations in Embedded System Education
 

Último

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 

Último (20)

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 

Class, object and inheritance in python

  • 1. OOPs CONCEPT IN PYTHON SANTOSH VERMA Faculty Development Program: Python Programming JK Lakshmipat University, Jaipur (3-7, June 2019)
  • 2. Important Note  Please remember that Python completely works on indentation.  Use the tab key to provide indentation to your code.
  • 3. Classes and Objects Classes Just like every other Object Oriented Programming language Python supports classes. Let’s look at some points on Python classes. Classes are created by keyword class.  Attributes are the variables that belong to class.  Attributes are always public and can be accessed using dot (.) operator. Eg.: Myclass.Myattribute
  • 4. # A simple example class class Test: # A sample method def fun(self): print("Hello") # Driver code obj = Test() obj.fun() Output: Hello
  • 5. The self  Class methods must have an extra first parameter in method definition. do not give a value for this parameter when we call the method, Python provides it.  If we have a method which takes no arguments, then we still have to one argument – the self. See fun() in above simple example.  This is similar to this pointer in C++ and this reference in Java.  When we call a method of this object as myobject.method(arg1, arg2), is automatically converted by Python into MyClass.method(myobject, arg2) – this is all the special self is about.
  • 6. # creates a class named MyClass class MyClass: # assign the values to the MyClass attributes number = 0 name = "noname" def Main(): # Creating an object of the MyClass.Here, 'me' is the object me = MyClass() # Accessing the attributes of MyClass, using the dot(.) operator me.number = 310 me.name = "Santosh" # str is an build-in function that, creates an string print(me.name + " " + str(me.number)) # telling python that there is main in the program. if __name__=='__main__': Main() Output: Santosh 310
  • 7.  The __init__ method The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) p = Person(‘Santosh') p.say_hi()
  • 8. Methods  Method is a bunch of code that is intended to perform a particular task in your Python’s code.  Function that belongs to a class is called an Method.  All methods require ‘self’ first parameter. If you have coded in other OOP language you can think of ‘self’ as the ‘this’ keyword which is used for the current object. It unhides the current instance variable. ’self’ mostly work like ‘this’.  ‘def’ keyword is used to create a new method.
  • 9. class Vector2D: x = 0.0 y = 0.0 # Creating a method named Set def Set(self, x, y): self.x = x self.y = y def Main(): # vec is an object of class Vector2D vec = Vector2D() # Passing values to the function Set # by using dot(.) operator. vec.Set(5, 6) print("X: " + vec.x + ", Y: " + vec.y) if __name__=='__main__': Main() Output: X: 5, Y: 6
  • 11. Inheritance  Inheritance is the capability of one class to derive or inherit the properties from some another class. The benefits of inheritance are:  It represents real-world relationships well.  It provides reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it.  It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.  Inheritance is defined as a way in which a particular class inherits features from its base class.  Base class is also knows as ‘Superclass’ and the class which inherits from the Superclass is knows as ‘Subclass’
  • 12.  # Syntax for inheritance  class derived-classname(superclass-name)
  • 13. class Person(object): # class Person: of Python 3.x is same as defined here. def __init__(self, name): # Constructor self.name = name def getName(self): # To get name return self.name def isEmployee(self): # To check if this person is employee return False # Inherited or Sub class (Note Person in bracket) class Employee(Person): def isEmployee(self): # Here we return true return True # Driver code emp = Person(“Ram") # An Object of Person print(emp.getName(), emp.isEmployee()) emp = Employee(“Shyam") # An Object of Employee print(emp.getName(), emp.isEmployee()) OUTPUT: Ram False Shyam True
  • 14. Explore more on Inheritance Type Thank You!