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)

CouchDB Map/Reduce
CouchDB Map/ReduceCouchDB Map/Reduce
CouchDB Map/Reduce
Oliver Kurowski
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
Damian T. Gordon
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Bypassing Windows Security Functions(ja)
Bypassing Windows Security Functions(ja)Bypassing Windows Security Functions(ja)
Bypassing Windows Security Functions(ja)
abend_cve_9999_0001
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
Adeel Rasheed
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
 
File Handling in Python
File Handling in PythonFile Handling in Python
File Handling in Python
International Institute of Information Technology (I²IT)
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
Karudaiyar Ganapathy
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
ppd1961
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Concept of OOPS with real life examples
Concept of OOPS with real life examplesConcept of OOPS with real life examples
Concept of OOPS with real life examples
Neha Sharma
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
AkshayAggarwal79
 
COLLECTIONS.pptx
COLLECTIONS.pptxCOLLECTIONS.pptx
COLLECTIONS.pptx
SruthyPJ
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
SIVASHANKARIRAJAN
 
Adbms 23 distributed database design
Adbms 23 distributed database designAdbms 23 distributed database design
Adbms 23 distributed database design
Vaibhav Khanna
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
baabtra.com - No. 1 supplier of quality freshers
 
Basic Concepts Of OOPS/OOPS in Java,C++
Basic Concepts Of OOPS/OOPS in Java,C++Basic Concepts Of OOPS/OOPS in Java,C++
Basic Concepts Of OOPS/OOPS in Java,C++
Guneesh Basundhra
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
colleges
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Bypassing Windows Security Functions(ja)
Bypassing Windows Security Functions(ja)Bypassing Windows Security Functions(ja)
Bypassing Windows Security Functions(ja)
abend_cve_9999_0001
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
Adeel Rasheed
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
ppd1961
 
Concept of OOPS with real life examples
Concept of OOPS with real life examplesConcept of OOPS with real life examples
Concept of OOPS with real life examples
Neha Sharma
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
AkshayAggarwal79
 
COLLECTIONS.pptx
COLLECTIONS.pptxCOLLECTIONS.pptx
COLLECTIONS.pptx
SruthyPJ
 
Adbms 23 distributed database design
Adbms 23 distributed database designAdbms 23 distributed database design
Adbms 23 distributed database design
Vaibhav Khanna
 
Basic Concepts Of OOPS/OOPS in Java,C++
Basic Concepts Of OOPS/OOPS in Java,C++Basic Concepts Of OOPS/OOPS in Java,C++
Basic Concepts Of OOPS/OOPS in Java,C++
Guneesh Basundhra
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
colleges
 

Viewers also liked (12)

Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
Damian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
Python: Manager Objects
Python: Manager ObjectsPython: Manager Objects
Python: Manager Objects
Damian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
Damian T. Gordon
 
Python: Design Patterns
Python: Design PatternsPython: Design Patterns
Python: Design Patterns
Damian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
Damian T. Gordon
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
Damian T. Gordon
 
Python: Access Control
Python: Access ControlPython: Access Control
Python: Access Control
Damian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
Damian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
Damian T. Gordon
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
Damian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
Damian T. Gordon
 
Ad

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

Python 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptxPython 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMINGOOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overlodingRegex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
Module 4.pptx
Module 4.pptxModule 4.pptx
Module 4.pptx
charancherry185493
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
ID Bilişim ve Ticaret Ltd. Şti.
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
NuurAxmed2
 
object oriented porgramming using Java programming
object oriented porgramming using Java programmingobject oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Module IV_updated(old).pdf
Module IV_updated(old).pdfModule IV_updated(old).pdf
Module IV_updated(old).pdf
R.K.College of engg & Tech
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
slides11-objects_and_classes in python.pptx
slides11-objects_and_classes in python.pptxslides11-objects_and_classes in python.pptx
slides11-objects_and_classes in python.pptx
debasisdas225831
 
مقدمة بايثون .pptx
مقدمة بايثون .pptxمقدمة بايثون .pptx
مقدمة بايثون .pptx
AlmutasemBillahAlwas
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
Python-Classes.pptx
Python-Classes.pptxPython-Classes.pptx
Python-Classes.pptx
Karudaiyar Ganapathy
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in python
tuan vo
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
Ranel Padon
 
oopinpyhtonnew-140722060241-phpapp01.pptx
oopinpyhtonnew-140722060241-phpapp01.pptxoopinpyhtonnew-140722060241-phpapp01.pptx
oopinpyhtonnew-140722060241-phpapp01.pptx
smartashammari
 
Python 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptxPython 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMINGOOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overlodingRegex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
object oriented porgramming using Java programming
object oriented porgramming using Java programmingobject oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
slides11-objects_and_classes in python.pptx
slides11-objects_and_classes in python.pptxslides11-objects_and_classes in python.pptx
slides11-objects_and_classes in python.pptx
debasisdas225831
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in python
tuan vo
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
Ranel Padon
 
oopinpyhtonnew-140722060241-phpapp01.pptx
oopinpyhtonnew-140722060241-phpapp01.pptxoopinpyhtonnew-140722060241-phpapp01.pptx
oopinpyhtonnew-140722060241-phpapp01.pptx
smartashammari
 
Ad

More from Damian T. Gordon (20)

Introduction to Prompts and Prompt Engineering
Introduction to Prompts and Prompt EngineeringIntroduction to Prompts and Prompt Engineering
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem SolvingTRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAISome Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Some Common Errors that Generative AI ProducesSome Common Errors that Generative AI Produces
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data ScienceThe Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft WindowsA History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Writing an Abstract: A Question-based ApproachWriting an Abstract: A Question-based Approach
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Using GenAI for Universal Design for LearningUsing GenAI for Universal Design for Learning
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software DesignA CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
A History of Versions of the Apple MacOSA History of Versions of the Apple MacOS
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
68 Ways that Data Science and AI can help address the UN Sustainability Goals68 Ways that Data Science and AI can help address the UN Sustainability Goals
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Copyright and Creative Commons ConsiderationsCopyright and Creative Commons Considerations
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and SuggestionsExam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Studying and Notetaking: Some SuggestionsStudying and Notetaking: Some Suggestions
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and ActivitiesThe Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural NetworksHyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and ArtistsEarly 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial IntelligenceAn Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 
Introduction to Prompts and Prompt Engineering
Introduction to Prompts and Prompt EngineeringIntroduction to Prompts and Prompt Engineering
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem SolvingTRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAISome Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Some Common Errors that Generative AI ProducesSome Common Errors that Generative AI Produces
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data ScienceThe Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft WindowsA History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Writing an Abstract: A Question-based ApproachWriting an Abstract: A Question-based Approach
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Using GenAI for Universal Design for LearningUsing GenAI for Universal Design for Learning
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software DesignA CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
A History of Versions of the Apple MacOSA History of Versions of the Apple MacOS
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
68 Ways that Data Science and AI can help address the UN Sustainability Goals68 Ways that Data Science and AI can help address the UN Sustainability Goals
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Copyright and Creative Commons ConsiderationsCopyright and Creative Commons Considerations
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and SuggestionsExam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Studying and Notetaking: Some SuggestionsStudying and Notetaking: Some Suggestions
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and ActivitiesThe Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural NetworksHyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and ArtistsEarly 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial IntelligenceAn Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 

Recently uploaded (20)

How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 

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.