Migrating to Object-Oriented Programs

Slides:



Advertisements
Similar presentations
Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Advertisements

OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Starter  Identify the separate tasks to be performed in the programming task below (break it down into numbered sections).  A program is needed to prompt.
Classes and Objects, Part 1 Victor Norman CS104. Reading Quiz, Q1 A class definition define these two elements. A. attributes and functions B. attributes.
Guide to Programming with Python
Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game.
Python, Part 2. Python Object Equality x == y x is y In Java: (x.equals(y)) (x == y)
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris
Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
Python – Procedures If the same piece of code needs to be used several times we can use a loop - but only if those times are all together. If you need.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Classes and Objects The basics. Object-oriented programming Python is an object-oriented programming language, which means that it provides features that.
Classes 1 COMPSCI 105 S Principles of Computer Science.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
PYTHON OBJECTS & CLASSES. What is an object? The abstract idea of anything What is in an object: Attributes Characteristics Represented by internal variables.
If the same piece of code needs to be used several times we can use a loop – but only if those times are all together. If you need to run the same bit.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Section 6.1 CS 106 Victor Norman IQ Unknown. The Big Q What do we get by being able to define a class?! Or Do we really need this?!
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
The single most important skill for a computer programmer is problem solving Problem solving means the ability to formulate problems, think creatively.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Module 9: Operator overloading #1 2000/01Scientific Computing in OOCourse code 3C59 Module 9: Operator Overloading In this module we will cover Overloading.
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CSC 108H: Introduction to Computer Programming Summer 2012 Marek Janicki.
Objects in Python: Part 2 Damian Gordon. Initialising an Object.
Object-Orientated Design (Summary)
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Adapted from slides by Marty Stepp and Stuart Reges
Modules and Packages Damian Gordon.
C++ coding standard suggestion… Separate reasoning from action, in every block. Hi, this talk is to suggest a rule (or guideline) to simplify C++ code.
CS-104 Final Exam Review Victor Norman.
Tutorial Lecture for EE562 Artificial Intelligence for Engineers
Functions CIS 40 – Introduction to Programming in Python
University of Washington Computer Programming I
Chapter 16 – Programming your App’s Memory
Object Oriented Programming
Python Classes By Craig Pennell.
Guide to Programming with Python
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
Adapted from slides by Marty Stepp and Stuart Reges
User Defined Classes CS F.
Teach A-Level Computer Science: Object-Oriented Programming in Python
Coding Concepts (Sub- Programs)
Week 8 Classes and Objects
Adapted from slides by Marty Stepp and Stuart Reges
Object Oriented Programming in Python
Basic Inheritance Damian Gordon.
Classes, Objects and lists
Recursion Taken from notes by Dr. Neil Moore
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
OOP Python Inheritance
Access Control Damian Gordon.
A Level Computer Science Topic 6: Introducing OOP
Object-Oriented Design AND CLASS PROPERTIES
Functions, Procedures, and Abstraction
Presentation transcript:

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,2) (2,2) (1,1) (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,2) (2,2) p3 p2 p0 p1 (1,1) (2,1)

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,2) (2,2) p3 p2 p0 p1 (1,1) (2,1) [(1,1),(1,2),(2,2),(2,1)] + [(1,1)]

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  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

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): # 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): # 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 = "" Red

Object-Oriented Programming So now we can run as follows: redcolour = Colour("#FF0000", "Red") print(redcolour.get_name()) redcolour._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.