SlideShare a Scribd company logo
Migrating to
Object-Oriented Programs
Damian Gordon
Object-Oriented Programming
• Let’s start by stating the obvious, if we are designing software
and it is clear there are different types of objects, then each
different object type should be modelled as a separate class.
• Are objects always necessary? If we are just modelling data,
maybe an array is all we need, and if we are just modelling
behaviour, maybe a method is all we need; but if we are
modelling data and behaviour, an object might make sense.
Object-Oriented Programming
• When programming, it’s a good idea to start simple and grow
your solution to something more complex instead of starting
off with something too tricky immediately.
• So we might start off the program with a few variables, and as
we add functionality and features, we can start to think about
creating objects from the evolved design.
Object-Oriented Programming
• Let’s imagine we are creating a program to model polygons in
2D space, each point would be modelled using a pair as an X
and Y co-ordinate (x, y).
•
• So a square could be
– square = [(1,1),(1,2),(2,2),(2,1)]
• This is an array of tuples (pairs).
(1,1)
(2,2)(1,2)
(2,1)
Object-Oriented Programming
• To calculate the distance between two points:
import math
def distance(p1, p2):
return math.sqrt(
(p1[0] – p2[0])**2 + (p1[1] – p2[1])**2)
# END distance
d = √(x2 – x1)2 + (y2 – y1)2
Object-Oriented Programming
• And then to calculate the perimeter:
• Get the distance from:
– p0 to p1
– p1 to p2
– p2 to p3
– p3 to p0
• So we can create an array of the distances to loop through:
– points = [p0, p1, p2, p3, p0]
(1,1)
(2,2)(1,2)
(2,1)
p0 p1
p3 p2
Object-Oriented Programming
• And then to calculate the perimeter:
• So to create this array:
– points = [p0, p1, p2, p3, p0]
• All we need to do is:
– Points = polygon + [polygon[0]]
[(1,1),(1,2),(2,2),(2,1)] + [(1,1)]
(1,1)
(2,2)(1,2)
(2,1)
p0 p1
p3 p2
Object-Oriented Programming
• And then to calculate the perimeter
def perimeter(polygon):
perimeter = 0
points = polygon + [polygon[0]]
for i in range(len(polygon)):
perimeter += distance(points[i], points[i+1])
# ENDFOR
return perimeter
# END perimeter
Object-Oriented Programming
• Now to run the program we do:
>>> square = [(1,1),(1,2),(2,2),(2,1)]
>>> perimeter(square)
>>> square2 = [(1,1),(1,4),(4,4),(4,1)]
>>> perimeter(square2)
Object-Oriented Programming
• So does it make sense to collect all the attributes and methods
into a single class?
• Probably!
Object-Oriented Programming
import math
class Point:
def _ _init_ _(self, x, y):
self.x = x
self.y = y
# END init
Continued 
Object-Oriented Programming
def distance(self, p2):
return math.sqrt(
(self.x – p2.x)**2 + (self.y – p2.y)**2)
# END distance
# END class point
 Continued
Object-Oriented Programming
class Polygon:
def _ _init_ _(self):
self.vertices = []
# END init
def add_point(self, point):
self.vertices.append((point))
# END add_point
Continued 
Object-Oriented Programming
def perimeter(self):
perimeter = 0
points = self.vertices + [self.vertices[0]]
for i in range(len(self.vertices)):
perimeter += points[i].distance(points[i+1])
# ENDFOR
return perimeter
# END perimeter
# END class perimeter
Continued 
Object-Oriented Programming
• Now to run the program we do:
>>> square = Polygon()
>>> square.add_point(Point(1,1))
>>> square.add_point(Point(1,2))
>>> square.add_point(Point(2,2))
>>> square.add_point(Point(2,1))
>>> print("Polygon perimeter is", square.perimeter())
Object-Oriented Programming
Procedural Version
>>> square =
[(1,1),(1,2),(2,2),(2,1)]
>>> perimeter(square)
Object-Oriented Version
>>> square = Polygon()
>>> square.add_point(Point(1,1))
>>> square.add_point(Point(1,2))
>>> square.add_point(Point(2,2))
>>> square.add_point(Point(2,1))
>>> print("Polygon perimeter
is", square.perimeter())
Object-Oriented Programming
• So the object-oriented version certainly isn’t more compact
than the procedural version, but it is clearer in terms of what is
happening.
• Good programming is clear programming, it’s better to have a
lot of lines of code, if it makes things clearer, because someone
else will have to modify your code at some point in the future.
Using Properties
to add behaviour
Object-Oriented Programming
• Imagine we wrote code to store a colour and a hex value:
class Colour:
def _ _init__(self, rgb_value, name):
self.rgb_value = rgb_value
self.name = name
# END _ _init_ _
# END class.
Object-Oriented Programming
• So we would run this as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.name, "is", redcolour.rgb_value)
Object-Oriented Programming
• So we would run this as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.name, "is", redcolour.rgb_value)
Red is #FF0000
Object-Oriented Programming
• So we would run this as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.name, "is", redcolour.rgb_value)
Redcolour.name = “Bright Red”
print(redcolour.name)
Red is #FF0000
Object-Oriented Programming
• So we would run this as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.name, "is", redcolour.rgb_value)
Redcolour.name = “Bright Red”
print(redcolour.name)
Red is #FF0000
Bright Red
Object-Oriented Programming
• Sometimes we like to have methods to set (and get) the values
of the attributes, these are called getters and setters:
– set_name()
– get_name()
Object-Oriented Programming
class Colour:
def _ _init_ _(self, rgb_value, name):
self._rgb_value = rgb_value
self._name = name
# END _ _init_ _
def set_name(self, name):
self._name = name
# END set_name
def get_name(self):
return self._name
# END get_name
# END class.
Object-Oriented Programming
class Colour:
def _ _init_ _(self, rgb_value, name):
self._rgb_value = rgb_value
self._name = name
# END _ _init_ _
def set_name(self, name):
self._name = name
# END set_name
def get_name(self):
return self._name
# END get_name
# END class.
The __init__ class is the same as before,
except the internal variable names are
now preceded by underscores to indicate
that we don’t want to access them directly
The set_name class sets the name variable
instead of doing it the old way:
x._name = “Red”
The get_name class gets the name variable
instead of doing it the old way:
Print(x._name)
Object-Oriented Programming
• This works fine, and we can get the colour name in two
different ways:
– print(redcolour._name)
– print(redcolour.get_name())
Object-Oriented Programming
• This works fine, and we can get the colour name in two
different ways:
– print(redcolour._name)
– print(redcolour.get_name())
• The only difference is that we can add additionally
functionality easily into the get_name() method.
Object-Oriented Programming
• So we could add a check into the get_name to see if the name variable
is set to blank:
def get_name(self):
if self._name == "":
return "There is a blank value"
else:
return self._name
# ENDIF;
# END get_name
Object-Oriented Programming
• So now we can run as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.get_name())
Object-Oriented Programming
• So now we can run as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.get_name())
Red
Object-Oriented Programming
• So now we can run as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.get_name())
redcolour._name = ""
print(redcolour.get_name())
Red
Object-Oriented Programming
• So now we can run as follows:
redcolour = Colour("#FF0000", "Red")
print(redcolour.get_name())
redcolour._name = ""
print(redcolour.get_name())
Red
There is a blank value
Object-Oriented Programming
• But that only works if we do this:
– print(redcolour.get_name())
• What if we have a load of code written already that does this?
– print(redcolour._name)
Object-Oriented Programming
• But that only works if we do this:
– print(redcolour.get_name())
• What if we have a load of code written already that does this?
– print(redcolour._name)
• Python provides us with a magic function that takes care of
this, and it’s called property.
Object-Oriented Programming
• So what does property do?
• property forces the get_name() method to be run every
time a program requests the value of name, and property
forces the set_name() method to be run every time a
program assigns a new value to name.
Object-Oriented Programming
• We just add the following line in at the end of the class:
name = property(_get_name, _set_name)
• And then whichever way a program tries to get or set a value,
the methods will be executed.
More details
on Properties
Object-Oriented Programming
• The property function can accept two more parameters, a
deletion function and a docstring for the property. So in total
the property can take:
– A get function
– A set function
– A delete function
– A docstring
Object-Oriented Programming
class ALife:
def __init__(self, alife, value):
self.alife = alife
self.value = value
def _get_alife(self):
print("You are getting a life")
return self.alife
def _set_alife(self, value):
print("You are getting a life {}".format(value))
self._alife = value
def _del_alife(self, value):
print("You have deleted one life")
del self._alife
MyLife = property(_get_alife, _set_alife, _del_alife, “DocStrings:
This is a life property")
# END class.
Object-Oriented Programming
>>> help(ALife)
Help on ALife in module __main__ object:
class ALife(builtins.object)
| Methods defined here:
| __init__(self, alife, value)
| Initialize self. See help(type(self)) for accurate signature.
| -------------------------------------------------------------------
---
| Data descriptors defined here:
| MyLife
| DocStrings: This is a life property
| __dict__
| dictionary for instance variables (if defined)
| __weakref__
| list of weak references to the object (if defined)
etc.

More Related Content

What's hot (20)

PPTX
Introduction to Machine Learning
Knowledge And Skill Forum
 
PDF
Unsupervised Machine Learning Ml And How It Works
SlideTeam
 
PPTX
Machine learning clustering
CosmoAIMS Bassett
 
PPTX
Traveling salesman problem
Jayesh Chauhan
 
PPTX
Graph coloring problem(DAA).pptx
Home
 
DOC
Chapter 5 (final)
Nateshwar Kamlesh
 
PPT
AI Lecture 7 (uncertainty)
Tajim Md. Niamat Ullah Akhund
 
PPTX
Prediction of House Sales Price
Anirvan Ghosh
 
PPTX
And or graph
Ali A Jalil
 
PDF
Production System in AI
Bharat Bhushan
 
PPTX
Predicate logic
Harini Balamurugan
 
PDF
Graph Based Pattern Recognition
Nicola Strisciuglio
 
PPTX
ProLog (Artificial Intelligence) Introduction
wahab khan
 
PDF
Expert systems Artificial Intelligence
itti rehan
 
PPTX
Compiler Design Introduction
Thapar Institute
 
PPTX
House Sale Price Prediction
sriram30691
 
PPTX
PPT on Data Science Using Python
NishantKumar1179
 
PPTX
Predicting house price
Divya Tiwari
 
PPTX
Prolog Programming : Basics
Mitul Desai
 
PPTX
resolution in the propositional calculus
Anju Kanjirathingal
 
Introduction to Machine Learning
Knowledge And Skill Forum
 
Unsupervised Machine Learning Ml And How It Works
SlideTeam
 
Machine learning clustering
CosmoAIMS Bassett
 
Traveling salesman problem
Jayesh Chauhan
 
Graph coloring problem(DAA).pptx
Home
 
Chapter 5 (final)
Nateshwar Kamlesh
 
AI Lecture 7 (uncertainty)
Tajim Md. Niamat Ullah Akhund
 
Prediction of House Sales Price
Anirvan Ghosh
 
And or graph
Ali A Jalil
 
Production System in AI
Bharat Bhushan
 
Predicate logic
Harini Balamurugan
 
Graph Based Pattern Recognition
Nicola Strisciuglio
 
ProLog (Artificial Intelligence) Introduction
wahab khan
 
Expert systems Artificial Intelligence
itti rehan
 
Compiler Design Introduction
Thapar Institute
 
House Sale Price Prediction
sriram30691
 
PPT on Data Science Using Python
NishantKumar1179
 
Predicting house price
Divya Tiwari
 
Prolog Programming : Basics
Mitul Desai
 
resolution in the propositional calculus
Anju Kanjirathingal
 

Viewers also liked (13)

PPTX
Python: Polymorphism
Damian T. Gordon
 
PPTX
Creating Objects in Python
Damian T. Gordon
 
PPTX
Python: Manager Objects
Damian T. Gordon
 
PPTX
Python: Multiple Inheritance
Damian T. Gordon
 
PPTX
Introduction to Python programming
Damian T. Gordon
 
PPTX
Object-Orientated Design
Damian T. Gordon
 
PPTX
Python: Design Patterns
Damian T. Gordon
 
PPTX
Python: Basic Inheritance
Damian T. Gordon
 
PPTX
Python: Third-Party Libraries
Damian T. Gordon
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PPTX
Python: The Iterator Pattern
Damian T. Gordon
 
PPTX
Python: Access Control
Damian T. Gordon
 
PPTX
The Extreme Programming (XP) Model
Damian T. Gordon
 
Python: Polymorphism
Damian T. Gordon
 
Creating Objects in Python
Damian T. Gordon
 
Python: Manager Objects
Damian T. Gordon
 
Python: Multiple Inheritance
Damian T. Gordon
 
Introduction to Python programming
Damian T. Gordon
 
Object-Orientated Design
Damian T. Gordon
 
Python: Design Patterns
Damian T. Gordon
 
Python: Basic Inheritance
Damian T. Gordon
 
Python: Third-Party Libraries
Damian T. Gordon
 
Python: Modules and Packages
Damian T. Gordon
 
Python: The Iterator Pattern
Damian T. Gordon
 
Python: Access Control
Damian T. Gordon
 
The Extreme Programming (XP) Model
Damian T. Gordon
 
Ad

Similar to Python: Migrating from Procedural to Object-Oriented Programming (20)

PPTX
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
PPTX
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
PPTX
VTU Python Module 5 , Class and Objects and Debugging
rickyghoshiit
 
PPTX
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
PPTX
Module 4.pptx
charancherry185493
 
PDF
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
ID Bilişim ve Ticaret Ltd. Şti.
 
PPT
07slide.ppt
NuurAxmed2
 
PPTX
object oriented porgramming using Java programming
afsheenfaiq2
 
PDF
Module IV_updated(old).pdf
R.K.College of engg & Tech
 
PDF
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
PPTX
slides11-objects_and_classes in python.pptx
debasisdas225831
 
PPTX
classes and objects of python object oriented
VineelaThonduri
 
PPTX
مقدمة بايثون .pptx
AlmutasemBillahAlwas
 
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
PDF
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
PPTX
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
PPTX
Python-Classes.pptx
Karudaiyar Ganapathy
 
PPTX
Introduce oop in python
tuan vo
 
PPTX
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
VTU Python Module 5 , Class and Objects and Debugging
rickyghoshiit
 
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
Module 4.pptx
charancherry185493
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
ID Bilişim ve Ticaret Ltd. Şti.
 
07slide.ppt
NuurAxmed2
 
object oriented porgramming using Java programming
afsheenfaiq2
 
Module IV_updated(old).pdf
R.K.College of engg & Tech
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
slides11-objects_and_classes in python.pptx
debasisdas225831
 
classes and objects of python object oriented
VineelaThonduri
 
مقدمة بايثون .pptx
AlmutasemBillahAlwas
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
Python-Classes.pptx
Karudaiyar Ganapathy
 
Introduce oop in python
tuan vo
 
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Ad

More from Damian T. Gordon (20)

PPTX
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
PPTX
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
PPTX
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
PPTX
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
PPTX
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
PPTX
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
PPTX
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
PPTX
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
PPTX
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
DOC
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
PPTX
A History of Versions of the Apple MacOS
Damian T. Gordon
 
PPTX
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
PPTX
Copyright and Creative Commons Considerations
Damian T. Gordon
 
PPTX
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
PPTX
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
PPTX
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
PPTX
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
PPTX
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
PPTX
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
PPTX
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
Damian T. Gordon
 
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 

Recently uploaded (20)

PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
Dimensions of Societal Planning in Commonism
StefanMz
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 

Python: Migrating from Procedural to Object-Oriented Programming

  • 2. Object-Oriented Programming • Let’s start by stating the obvious, if we are designing software and it is clear there are different types of objects, then each different object type should be modelled as a separate class. • Are objects always necessary? If we are just modelling data, maybe an array is all we need, and if we are just modelling behaviour, maybe a method is all we need; but if we are modelling data and behaviour, an object might make sense.
  • 3. Object-Oriented Programming • When programming, it’s a good idea to start simple and grow your solution to something more complex instead of starting off with something too tricky immediately. • So we might start off the program with a few variables, and as we add functionality and features, we can start to think about creating objects from the evolved design.
  • 4. Object-Oriented Programming • Let’s imagine we are creating a program to model polygons in 2D space, each point would be modelled using a pair as an X and Y co-ordinate (x, y). • • So a square could be – square = [(1,1),(1,2),(2,2),(2,1)] • This is an array of tuples (pairs). (1,1) (2,2)(1,2) (2,1)
  • 5. Object-Oriented Programming • To calculate the distance between two points: import math def distance(p1, p2): return math.sqrt( (p1[0] – p2[0])**2 + (p1[1] – p2[1])**2) # END distance d = √(x2 – x1)2 + (y2 – y1)2
  • 6. Object-Oriented Programming • And then to calculate the perimeter: • Get the distance from: – p0 to p1 – p1 to p2 – p2 to p3 – p3 to p0 • So we can create an array of the distances to loop through: – points = [p0, p1, p2, p3, p0] (1,1) (2,2)(1,2) (2,1) p0 p1 p3 p2
  • 7. Object-Oriented Programming • And then to calculate the perimeter: • So to create this array: – points = [p0, p1, p2, p3, p0] • All we need to do is: – Points = polygon + [polygon[0]] [(1,1),(1,2),(2,2),(2,1)] + [(1,1)] (1,1) (2,2)(1,2) (2,1) p0 p1 p3 p2
  • 8. Object-Oriented Programming • And then to calculate the perimeter def perimeter(polygon): perimeter = 0 points = polygon + [polygon[0]] for i in range(len(polygon)): perimeter += distance(points[i], points[i+1]) # ENDFOR return perimeter # END perimeter
  • 9. Object-Oriented Programming • Now to run the program we do: >>> square = [(1,1),(1,2),(2,2),(2,1)] >>> perimeter(square) >>> square2 = [(1,1),(1,4),(4,4),(4,1)] >>> perimeter(square2)
  • 10. Object-Oriented Programming • So does it make sense to collect all the attributes and methods into a single class? • Probably!
  • 11. Object-Oriented Programming import math class Point: def _ _init_ _(self, x, y): self.x = x self.y = y # END init Continued 
  • 12. Object-Oriented Programming def distance(self, p2): return math.sqrt( (self.x – p2.x)**2 + (self.y – p2.y)**2) # END distance # END class point  Continued
  • 13. Object-Oriented Programming class Polygon: def _ _init_ _(self): self.vertices = [] # END init def add_point(self, point): self.vertices.append((point)) # END add_point Continued 
  • 14. Object-Oriented Programming def perimeter(self): perimeter = 0 points = self.vertices + [self.vertices[0]] for i in range(len(self.vertices)): perimeter += points[i].distance(points[i+1]) # ENDFOR return perimeter # END perimeter # END class perimeter Continued 
  • 15. Object-Oriented Programming • Now to run the program we do: >>> square = Polygon() >>> square.add_point(Point(1,1)) >>> square.add_point(Point(1,2)) >>> square.add_point(Point(2,2)) >>> square.add_point(Point(2,1)) >>> print("Polygon perimeter is", square.perimeter())
  • 16. Object-Oriented Programming Procedural Version >>> square = [(1,1),(1,2),(2,2),(2,1)] >>> perimeter(square) Object-Oriented Version >>> square = Polygon() >>> square.add_point(Point(1,1)) >>> square.add_point(Point(1,2)) >>> square.add_point(Point(2,2)) >>> square.add_point(Point(2,1)) >>> print("Polygon perimeter is", square.perimeter())
  • 17. Object-Oriented Programming • So the object-oriented version certainly isn’t more compact than the procedural version, but it is clearer in terms of what is happening. • Good programming is clear programming, it’s better to have a lot of lines of code, if it makes things clearer, because someone else will have to modify your code at some point in the future.
  • 19. Object-Oriented Programming • Imagine we wrote code to store a colour and a hex value: class Colour: def _ _init__(self, rgb_value, name): self.rgb_value = rgb_value self.name = name # END _ _init_ _ # END class.
  • 20. Object-Oriented Programming • So we would run this as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.name, "is", redcolour.rgb_value)
  • 21. Object-Oriented Programming • So we would run this as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.name, "is", redcolour.rgb_value) Red is #FF0000
  • 22. Object-Oriented Programming • So we would run this as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.name, "is", redcolour.rgb_value) Redcolour.name = “Bright Red” print(redcolour.name) Red is #FF0000
  • 23. Object-Oriented Programming • So we would run this as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.name, "is", redcolour.rgb_value) Redcolour.name = “Bright Red” print(redcolour.name) Red is #FF0000 Bright Red
  • 24. Object-Oriented Programming • Sometimes we like to have methods to set (and get) the values of the attributes, these are called getters and setters: – set_name() – get_name()
  • 25. Object-Oriented Programming class Colour: def _ _init_ _(self, rgb_value, name): self._rgb_value = rgb_value self._name = name # END _ _init_ _ def set_name(self, name): self._name = name # END set_name def get_name(self): return self._name # END get_name # END class.
  • 26. Object-Oriented Programming class Colour: def _ _init_ _(self, rgb_value, name): self._rgb_value = rgb_value self._name = name # END _ _init_ _ def set_name(self, name): self._name = name # END set_name def get_name(self): return self._name # END get_name # END class. The __init__ class is the same as before, except the internal variable names are now preceded by underscores to indicate that we don’t want to access them directly The set_name class sets the name variable instead of doing it the old way: x._name = “Red” The get_name class gets the name variable instead of doing it the old way: Print(x._name)
  • 27. Object-Oriented Programming • This works fine, and we can get the colour name in two different ways: – print(redcolour._name) – print(redcolour.get_name())
  • 28. Object-Oriented Programming • This works fine, and we can get the colour name in two different ways: – print(redcolour._name) – print(redcolour.get_name()) • The only difference is that we can add additionally functionality easily into the get_name() method.
  • 29. Object-Oriented Programming • So we could add a check into the get_name to see if the name variable is set to blank: def get_name(self): if self._name == "": return "There is a blank value" else: return self._name # ENDIF; # END get_name
  • 30. Object-Oriented Programming • So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name())
  • 31. Object-Oriented Programming • So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name()) Red
  • 32. Object-Oriented Programming • So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name()) redcolour._name = "" print(redcolour.get_name()) Red
  • 33. Object-Oriented Programming • So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name()) redcolour._name = "" print(redcolour.get_name()) Red There is a blank value
  • 34. Object-Oriented Programming • But that only works if we do this: – print(redcolour.get_name()) • What if we have a load of code written already that does this? – print(redcolour._name)
  • 35. Object-Oriented Programming • But that only works if we do this: – print(redcolour.get_name()) • What if we have a load of code written already that does this? – print(redcolour._name) • Python provides us with a magic function that takes care of this, and it’s called property.
  • 36. Object-Oriented Programming • So what does property do? • property forces the get_name() method to be run every time a program requests the value of name, and property forces the set_name() method to be run every time a program assigns a new value to name.
  • 37. Object-Oriented Programming • We just add the following line in at the end of the class: name = property(_get_name, _set_name) • And then whichever way a program tries to get or set a value, the methods will be executed.
  • 39. Object-Oriented Programming • The property function can accept two more parameters, a deletion function and a docstring for the property. So in total the property can take: – A get function – A set function – A delete function – A docstring
  • 40. Object-Oriented Programming class ALife: def __init__(self, alife, value): self.alife = alife self.value = value def _get_alife(self): print("You are getting a life") return self.alife def _set_alife(self, value): print("You are getting a life {}".format(value)) self._alife = value def _del_alife(self, value): print("You have deleted one life") del self._alife MyLife = property(_get_alife, _set_alife, _del_alife, “DocStrings: This is a life property") # END class.
  • 41. Object-Oriented Programming >>> help(ALife) Help on ALife in module __main__ object: class ALife(builtins.object) | Methods defined here: | __init__(self, alife, value) | Initialize self. See help(type(self)) for accurate signature. | ------------------------------------------------------------------- --- | Data descriptors defined here: | MyLife | DocStrings: This is a life property | __dict__ | dictionary for instance variables (if defined) | __weakref__ | list of weak references to the object (if defined)
  • 42. etc.