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

PPTX
Polish Notation In Data Structure
Meghaj Mallick
 
PPTX
Looping statements
Jaya Kumari
 
PPTX
Chapter 07 inheritance
Praveen M Jigajinni
 
PPT
Linked list
Harry Potter
 
PPTX
Unit 3 sp assembler
Deepmala Sharma
 
PPTX
Type casting in java
Farooq Baloch
 
PPTX
Data Type Conversion in C++
Danial Mirza
 
PPT
Introduction to method overloading & method overriding in java hdm
Harshal Misalkar
 
Polish Notation In Data Structure
Meghaj Mallick
 
Looping statements
Jaya Kumari
 
Chapter 07 inheritance
Praveen M Jigajinni
 
Linked list
Harry Potter
 
Unit 3 sp assembler
Deepmala Sharma
 
Type casting in java
Farooq Baloch
 
Data Type Conversion in C++
Danial Mirza
 
Introduction to method overloading & method overriding in java hdm
Harshal Misalkar
 

What's hot (20)

PPT
Breadth first search
Sazzad Hossain
 
PPT
Graphs bfs dfs
Jaya Gautam
 
PPTX
Single source Shortest path algorithm with example
VINITACHAUHAN21
 
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
PPT
Python modules
Shanmugapriya Dineshbabu
 
PPTX
Python Lambda Function
Md Soyaib
 
PPTX
Super keyword in java
Hitesh Kumar
 
PPS
Wrapper class
kamal kotecha
 
PPTX
Array of objects.pptx
RAGAVIC2
 
PDF
POO Java Chapitre 4 Heritage et Polymorphisme
Mouna Torjmen
 
PDF
Manipulators
Kamal Acharya
 
PPTX
Constructor in java
Hitesh Kumar
 
PPTX
Presentation on Breadth First Search (BFS)
Shuvongkor Barman
 
PPTX
Data structure in perl
sana mateen
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PPTX
Evaluation of prefix expression with example
GADAPURAMSAINIKHIL
 
PDF
C++ OOPS Concept
Boopathi K
 
PPTX
Properties and indexers in C#
Hemant Chetwani
 
PPTX
Python-DataAbstarction.pptx
Karudaiyar Ganapathy
 
PPTX
Typecasting in c
Tushar Shende
 
Breadth first search
Sazzad Hossain
 
Graphs bfs dfs
Jaya Gautam
 
Single source Shortest path algorithm with example
VINITACHAUHAN21
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Python modules
Shanmugapriya Dineshbabu
 
Python Lambda Function
Md Soyaib
 
Super keyword in java
Hitesh Kumar
 
Wrapper class
kamal kotecha
 
Array of objects.pptx
RAGAVIC2
 
POO Java Chapitre 4 Heritage et Polymorphisme
Mouna Torjmen
 
Manipulators
Kamal Acharya
 
Constructor in java
Hitesh Kumar
 
Presentation on Breadth First Search (BFS)
Shuvongkor Barman
 
Data structure in perl
sana mateen
 
9. Input Output in java
Nilesh Dalvi
 
Evaluation of prefix expression with example
GADAPURAMSAINIKHIL
 
C++ OOPS Concept
Boopathi K
 
Properties and indexers in C#
Hemant Chetwani
 
Python-DataAbstarction.pptx
Karudaiyar Ganapathy
 
Typecasting in c
Tushar Shende
 
Ad

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
Classes_and_Objects_in_Pythonoopsconcept.pptx
ARVINDVENKAT7
 
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
 
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Classes_and_Objects_in_Pythonoopsconcept.pptx
ARVINDVENKAT7
 
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
 

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
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
Trends in pediatric nursing .pptx
AneetaSharma15
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PDF
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
PDF
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
Trends in pediatric nursing .pptx
AneetaSharma15
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 

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.