SlideShare una empresa de Scribd logo
1 de 25
Introduce OOP in Python
Tuan Vo
Jan 2018
Remind the method upper() of a String
‘abc’ is data of s
upper() is a method of s
Note: all String can use
method upper()
String is a Built-in Data Type
String is called a Built-
in Data Type
String provides many
methods (capitalize,
center,count,decode,… )
The question:
Does Python allow us to create a data
type which can contains methods like
String ?
The answer:
The answer is “Yes”:
Python allow us to create our data types which
is called user-defined types. User- defined types
might contains data and methods like String.
Introduce User- defined types in Python
class Rectangle(object):
width = None
height = None
def CalculateArea(self):
return self.width * self.height
box = Rectangle()
box.width = 100.0
box.height = 200.0
print(box.CalculateArea())
Not worry about the syntax such as class or def CalculateArea(self) , or self
Just concentrate on how it works, I’ll mention the syntax later.
Introduce User- defined types in Python
A new type has been created with name: Rectangle
Type Rectangle contains two data: width and height
Type Rectangle contains a method : CalculateArea
The main idea is to manage data and methods in one place.
In this example , width and height of a Rectangle is
managed along with method CalculateArea inside user-
defined type Rectangle
User-defined type such as Rectangle is called class in Python.
Python provides much more functions for a class, will be mentioned in the
next slides.
Introduce Class in Python
Define a class
Instance Objects
Define a class in Python
Define the name for a class with key word: class Example class Rectangle:
Define the data (properties or fields or attributes): Example width = None
height = None
Define the method: The first parameter of
a method MUST be self.
All properties used inside a method must
be accessed via self. , such as self.width, self.height
def CalculateArea(self):
return self.width * self.height
Instance Objects
What is object?
=> Object is an instance of a class or it’s simple a variable with type is the class
class Rectangle:
width = None
height = None
def CalculateArea(self):
return self.width * self.height
box = Rectangle()#box is an instance of class Rectangle , box is called an object
box.width = 100.0
box.height = 200.0
print(box.CalculateArea())
box2 = Rectangle() #box2 is an instance of class Rectangle , box2 is called an object
box2.width = 250
box2.height = 200.0
print(box2.CalculateArea())
Set of get value for attributes of an Object
class Rectangle:
width = None
height = None
def CalculateArea(self):
return self.width * self.height
box = Rectangle()
box.width = 100.0 #set value of attribute width
box.height = 200.0 #set value of attribute height
print(box.width) #get value of attribute width
print(box.height) #get value of attribute height
The attributes of an object are sometime called properties or fields.
They handle data for an object.
Set value for an attribute: [NameOfObject].[NameOfAttribute] = [Value]
Get value of an attribute: [NameOfObject].[NameOfAttribute]
Example:
Call a method of an Object
Note: Do not need to include self when calling the
method of an instance of a class.
Although the methods of a class always require the first parameter is self, but it’s not necessary to pass
the parameter self to the method (this is syntax of Python )
box = Rectangle()
box.width = 100.0
box.height = 200.0
print(box.CalculateArea())
It’s simple to call the method after the name of an
instance and a dot.
[NameOfObject].[NameOfMethod]([Parameters])
Example box.CalculateArea as below:
Summary: Class vs Object
From now on, you can identify terms Class and Object.
A class is a definition of a user-defined type
A class defines its data (properties or fields, or
attributes) and methods
An object is an instance of a class.
An object is a variable that can work in a
program.
A class can have many objects ( many instances )
The ability to put data and methods into a class is called Encapsulation.
Encapsulation is the first characteristic of OOP.
OOP stands for: Object-oriented programming
The term object has been introduced.
The idea of OOP is try to create User-defined types (or class ) to reflect the
objects in real life when programming.
Example if an programming is written to manage a school, then some classes might be created
base on real life
class Student:
Name
EnrollYear
StudentCode
class Course:
StartDate
EndDate
class Subject:
SubjectName
Characteristic of OOP
Encapsulation is the first characteristic of OOP.
There are two more characteristic: Inheritance and Polymorphism.
Introduce Inheritance in Python
Inheritance is the ability to define a new class base on an existing class.
The existing class is called parent class (or supper ), and the new class is called child class.
See the example below:
class Rectangle:
width = None
height = None
def CalculateArea(self):
return self.width * self.height
class Cuboid(Rectangle):
length = None
def CalculateArea(self):
#reuse attributes width and height from Rectangle
return 2*self.width * self.height + 2*self.width* self.length + 2*self.height*self.length
c = Cuboid()
c.width = 10 #c reuses attribute width from Rectangle
c.height = 20 #c reuses attribute height from Rectangle
c.length = 5
print(c.CalculateArea())#the result will be 700
Introduce Inheritance in Python
1. The syntax to create new class: class [NameOfNewClass]([NameOfExistingClass]):
Example: class Cuboid(Rectangle):
2. An object of the new class (child class) can use all public attributes of the existing class
(supper/ parent class )
Example c = Cuboid(), c is an object of Cuboid and Cuboid is the child class of Rectangle, so c
can use attributes width and height of Rectangle.
3. The child class can define a new method has the same name, same parameter(s) as the parent,
this ability is called Overriding Methods. If an object of the child class calls the overriding
method, then the method of the child class will execute not the method of the parent class.
Example class Cuboid defines a new method CalculateArea which is defined in Rectangle,
when calling c.CalculateArea() then the method CalculateArea of Cuboid is called not
CalculateArea of Rectangle
Introduce Inheritance in Python
4. A class can be inherited from more than one class or a class might have more than one child
classes.
And a class can only inherit from one class.
Example: Class Sharp has two child classes Rectangle and Circle
class Sharp:
def Draw(self):
print('A Sharp is drawing')
class Rectangle:
width = None
height = None
def Draw(self):
print('A Rectangle is drawing')
def CalculateArea(self):
return self.width * self.height
class Circle:
radius = None
def Draw(self):
print('A Circle is drawing')
def CalculateArea(self):
return self.radius * 3.14
Introduce Polymorphism in Python
See the example below:
class Sharp:
def Draw(self):
print('A Sharp is drawing')
class Rectangle:
width = None
height = None
def Draw(self):
print('A Rectangle is drawing')
def CalculateArea(self):
return self.width * self.height
class Circle:
radius = None
def Draw(self):
print('A Circle is drawing')
def CalculateArea(self):
return self.radius * 3.14
s1 = Sharp() #s1 is declare as Sharp
s1.Draw() #will print 'A Sharp is drawing'
s1 = Rectangle() #s1 is now a Rectangle
s1.Draw() #will print 'A Rectangle is drawing'
s1 = Circle() #s1 is now a Circle
s1.Draw() #will print 'A Circle is drawing'
Introduce Polymorphism in Python
In the above example:
- Rectangle and Circle inherit from Sharp
- object s1 is first declared as an instance of Sharp
- Then s1 become an instance of Rectangle
- Then s1 become an instance of Circle
The ability s1 can become Rectangle or Circle is called Polymorphism.
In general:
Polymorphism is an ability of an object of an parent class which
can become instance of any of its child classes
Summary the characteristic of OOP in Python
Encapsulation
Inheritance
Polymorphism
You can see the most important
characteristic is encapsulation:
No encapsulation > No Inheritance
No Inheritance > No Polymorphism
They are all main characteristic in OOP. The next slides will
introduce some more special functionalities supported in
Python for OOP
Introduce Constructor in Class
A constructor is a special method in class which is called when creating an object.
A constructor method MUST be named __init__
A constructor method as the normal methods MUST contain the first parameter self
A class can have only one constructor method
class Rectangle:
width = None
height = None
def __init__(self):#a constructor to set width and height to 0
self.width = 0
self.height = 0
def CalculateArea(self):
return self.width * self.height
box = Rectangle()#width and height will be set to 0 in constructor
print(box.CalculateArea())#the result will be 0
Introduce Constructor in Class
Example constructor method can receive parameter(s).
class Rectangle:
width = None
height = None
def __init__(self,w,h):#a constructor to set width and height when creating an object
self.width = w
self.height = h
def CalculateArea(self):
return self.width * self.height
box = Rectangle(10,20)#set width to 10 and height to 20 when creating object
print(box.CalculateArea())#the result will be 200
Introduce Destructor in Class
A destructor is a special method in class which is called when destroying an object.
A constructor method MUST be named __del__( self )
class Rectangle:
width = None
height = None
def __del__(self):#a destructor
print('A rectangle is being destroyed')
def CalculateArea(self):
return self.width * self.height
box = Rectangle()
box.width = 10
box.height = 20
print(box.CalculateArea())#the result will be 200
# string 'A rectangle is being destroyed' will be printed
Content of file rectangle-4.py
Read more references to know more aspect of
OOP in Python
https://docs.python.org/3/tutorial/classes.html
https://www.tutorialspoint.com/python3/python_classes_objects.htm
https://www.python-course.eu/python3_object_oriented_programming.php
http://greenteapress.com/thinkpython/html/index.html
http://greenteapress.com/thinkpython/html/thinkpython016.html
http://greenteapress.com/thinkpython/html/thinkpython017.html
http://greenteapress.com/thinkpython/html/thinkpython018.html
Thank You
Author email: tuanv2t@gmail.com

Más contenido relacionado

La actualidad más candente

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 

La actualidad más candente (20)

Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Oop java
Oop javaOop java
Oop java
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Introduction to OOP in python inheritance
Introduction to OOP in python   inheritanceIntroduction to OOP in python   inheritance
Introduction to OOP in python inheritance
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 

Similar a Introduce oop in python

C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
Umar Farooq
 

Similar a Introduce oop in python (20)

Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxBasic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
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
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
 
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
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
 
Lecture 2 classes i
Lecture 2 classes iLecture 2 classes i
Lecture 2 classes i
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
OOPS.pptx
OOPS.pptxOOPS.pptx
OOPS.pptx
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
 
The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210The Ring programming language version 1.9 book - Part 84 of 210
The Ring programming language version 1.9 book - Part 84 of 210
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185
 

Último

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Introduce oop in python

  • 1. Introduce OOP in Python Tuan Vo Jan 2018
  • 2. Remind the method upper() of a String ‘abc’ is data of s upper() is a method of s Note: all String can use method upper()
  • 3. String is a Built-in Data Type String is called a Built- in Data Type String provides many methods (capitalize, center,count,decode,… )
  • 4. The question: Does Python allow us to create a data type which can contains methods like String ?
  • 5. The answer: The answer is “Yes”: Python allow us to create our data types which is called user-defined types. User- defined types might contains data and methods like String.
  • 6. Introduce User- defined types in Python class Rectangle(object): width = None height = None def CalculateArea(self): return self.width * self.height box = Rectangle() box.width = 100.0 box.height = 200.0 print(box.CalculateArea()) Not worry about the syntax such as class or def CalculateArea(self) , or self Just concentrate on how it works, I’ll mention the syntax later.
  • 7. Introduce User- defined types in Python A new type has been created with name: Rectangle Type Rectangle contains two data: width and height Type Rectangle contains a method : CalculateArea The main idea is to manage data and methods in one place. In this example , width and height of a Rectangle is managed along with method CalculateArea inside user- defined type Rectangle User-defined type such as Rectangle is called class in Python. Python provides much more functions for a class, will be mentioned in the next slides.
  • 8. Introduce Class in Python Define a class Instance Objects
  • 9. Define a class in Python Define the name for a class with key word: class Example class Rectangle: Define the data (properties or fields or attributes): Example width = None height = None Define the method: The first parameter of a method MUST be self. All properties used inside a method must be accessed via self. , such as self.width, self.height def CalculateArea(self): return self.width * self.height
  • 10. Instance Objects What is object? => Object is an instance of a class or it’s simple a variable with type is the class class Rectangle: width = None height = None def CalculateArea(self): return self.width * self.height box = Rectangle()#box is an instance of class Rectangle , box is called an object box.width = 100.0 box.height = 200.0 print(box.CalculateArea()) box2 = Rectangle() #box2 is an instance of class Rectangle , box2 is called an object box2.width = 250 box2.height = 200.0 print(box2.CalculateArea())
  • 11. Set of get value for attributes of an Object class Rectangle: width = None height = None def CalculateArea(self): return self.width * self.height box = Rectangle() box.width = 100.0 #set value of attribute width box.height = 200.0 #set value of attribute height print(box.width) #get value of attribute width print(box.height) #get value of attribute height The attributes of an object are sometime called properties or fields. They handle data for an object. Set value for an attribute: [NameOfObject].[NameOfAttribute] = [Value] Get value of an attribute: [NameOfObject].[NameOfAttribute] Example:
  • 12. Call a method of an Object Note: Do not need to include self when calling the method of an instance of a class. Although the methods of a class always require the first parameter is self, but it’s not necessary to pass the parameter self to the method (this is syntax of Python ) box = Rectangle() box.width = 100.0 box.height = 200.0 print(box.CalculateArea()) It’s simple to call the method after the name of an instance and a dot. [NameOfObject].[NameOfMethod]([Parameters]) Example box.CalculateArea as below:
  • 13. Summary: Class vs Object From now on, you can identify terms Class and Object. A class is a definition of a user-defined type A class defines its data (properties or fields, or attributes) and methods An object is an instance of a class. An object is a variable that can work in a program. A class can have many objects ( many instances ) The ability to put data and methods into a class is called Encapsulation. Encapsulation is the first characteristic of OOP. OOP stands for: Object-oriented programming The term object has been introduced. The idea of OOP is try to create User-defined types (or class ) to reflect the objects in real life when programming. Example if an programming is written to manage a school, then some classes might be created base on real life class Student: Name EnrollYear StudentCode class Course: StartDate EndDate class Subject: SubjectName
  • 14. Characteristic of OOP Encapsulation is the first characteristic of OOP. There are two more characteristic: Inheritance and Polymorphism.
  • 15. Introduce Inheritance in Python Inheritance is the ability to define a new class base on an existing class. The existing class is called parent class (or supper ), and the new class is called child class. See the example below: class Rectangle: width = None height = None def CalculateArea(self): return self.width * self.height class Cuboid(Rectangle): length = None def CalculateArea(self): #reuse attributes width and height from Rectangle return 2*self.width * self.height + 2*self.width* self.length + 2*self.height*self.length c = Cuboid() c.width = 10 #c reuses attribute width from Rectangle c.height = 20 #c reuses attribute height from Rectangle c.length = 5 print(c.CalculateArea())#the result will be 700
  • 16. Introduce Inheritance in Python 1. The syntax to create new class: class [NameOfNewClass]([NameOfExistingClass]): Example: class Cuboid(Rectangle): 2. An object of the new class (child class) can use all public attributes of the existing class (supper/ parent class ) Example c = Cuboid(), c is an object of Cuboid and Cuboid is the child class of Rectangle, so c can use attributes width and height of Rectangle. 3. The child class can define a new method has the same name, same parameter(s) as the parent, this ability is called Overriding Methods. If an object of the child class calls the overriding method, then the method of the child class will execute not the method of the parent class. Example class Cuboid defines a new method CalculateArea which is defined in Rectangle, when calling c.CalculateArea() then the method CalculateArea of Cuboid is called not CalculateArea of Rectangle
  • 17. Introduce Inheritance in Python 4. A class can be inherited from more than one class or a class might have more than one child classes. And a class can only inherit from one class. Example: Class Sharp has two child classes Rectangle and Circle class Sharp: def Draw(self): print('A Sharp is drawing') class Rectangle: width = None height = None def Draw(self): print('A Rectangle is drawing') def CalculateArea(self): return self.width * self.height class Circle: radius = None def Draw(self): print('A Circle is drawing') def CalculateArea(self): return self.radius * 3.14
  • 18. Introduce Polymorphism in Python See the example below: class Sharp: def Draw(self): print('A Sharp is drawing') class Rectangle: width = None height = None def Draw(self): print('A Rectangle is drawing') def CalculateArea(self): return self.width * self.height class Circle: radius = None def Draw(self): print('A Circle is drawing') def CalculateArea(self): return self.radius * 3.14 s1 = Sharp() #s1 is declare as Sharp s1.Draw() #will print 'A Sharp is drawing' s1 = Rectangle() #s1 is now a Rectangle s1.Draw() #will print 'A Rectangle is drawing' s1 = Circle() #s1 is now a Circle s1.Draw() #will print 'A Circle is drawing'
  • 19. Introduce Polymorphism in Python In the above example: - Rectangle and Circle inherit from Sharp - object s1 is first declared as an instance of Sharp - Then s1 become an instance of Rectangle - Then s1 become an instance of Circle The ability s1 can become Rectangle or Circle is called Polymorphism. In general: Polymorphism is an ability of an object of an parent class which can become instance of any of its child classes
  • 20. Summary the characteristic of OOP in Python Encapsulation Inheritance Polymorphism You can see the most important characteristic is encapsulation: No encapsulation > No Inheritance No Inheritance > No Polymorphism They are all main characteristic in OOP. The next slides will introduce some more special functionalities supported in Python for OOP
  • 21. Introduce Constructor in Class A constructor is a special method in class which is called when creating an object. A constructor method MUST be named __init__ A constructor method as the normal methods MUST contain the first parameter self A class can have only one constructor method class Rectangle: width = None height = None def __init__(self):#a constructor to set width and height to 0 self.width = 0 self.height = 0 def CalculateArea(self): return self.width * self.height box = Rectangle()#width and height will be set to 0 in constructor print(box.CalculateArea())#the result will be 0
  • 22. Introduce Constructor in Class Example constructor method can receive parameter(s). class Rectangle: width = None height = None def __init__(self,w,h):#a constructor to set width and height when creating an object self.width = w self.height = h def CalculateArea(self): return self.width * self.height box = Rectangle(10,20)#set width to 10 and height to 20 when creating object print(box.CalculateArea())#the result will be 200
  • 23. Introduce Destructor in Class A destructor is a special method in class which is called when destroying an object. A constructor method MUST be named __del__( self ) class Rectangle: width = None height = None def __del__(self):#a destructor print('A rectangle is being destroyed') def CalculateArea(self): return self.width * self.height box = Rectangle() box.width = 10 box.height = 20 print(box.CalculateArea())#the result will be 200 # string 'A rectangle is being destroyed' will be printed Content of file rectangle-4.py
  • 24. Read more references to know more aspect of OOP in Python https://docs.python.org/3/tutorial/classes.html https://www.tutorialspoint.com/python3/python_classes_objects.htm https://www.python-course.eu/python3_object_oriented_programming.php http://greenteapress.com/thinkpython/html/index.html http://greenteapress.com/thinkpython/html/thinkpython016.html http://greenteapress.com/thinkpython/html/thinkpython017.html http://greenteapress.com/thinkpython/html/thinkpython018.html
  • 25. Thank You Author email: tuanv2t@gmail.com