[go: up one dir, main page]

0% found this document useful (0 votes)
29 views12 pages

Modelling The World With Objects: Code Structure A Review

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views12 pages

Modelling The World With Objects: Code Structure A Review

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

LECTURE 6 Copyright Warning

COMMONWEALTH OF AUSTRALIA
MODELLING THE Copyright Regulation 1969
WARNING
WORLD WITH OBJECTS This material has been copied and communicated to
you by or on behalf of Curtin University of
Fundamentals of Programming - COMP1005 Technology pursuant to Part VB of the Copyright
Act 1968 (the Act)
The material in this communication may be subject
Department of Computing to copyright under the Act. Any further copying or
communication of this material by you may be the
Curtin University subject of copyright protection under the Act.
Updated 7/4/2020 Do not remove this notice

Learning Outcomes
•  Understand the main concepts in object-
oriented programming and their value
•  Read and explain object-oriented code
•  Apply and create simple object-oriented CODE STRUCTURE
Python code A REVIEW
Fundamentals of Programming
Lecture 6

3 4
Code Structure
•  Across the semester we've learnt many
elements of coding:
•  Control structures: if/else/elif, for loops, while loops
•  Creating and using functions
•  Creating and using modules
•  Python style: PEP-8, "readability counts"
•  Data types: int, float, string, list, array, set, dictionary
•  Files: text, csv
•  Key packages: numpy, scipy, matplotlib, pandas, random
•  Environments: python scripts, command lines, bash scripts, jupyter
notebooks

5 Fundamentals_Lecture10 6

Fundamentals_Lecture10 7 Fundamentals_Lecture10 8
Fundamentals_Lecture10 9 Fundamentals_Lecture10 10

General Code Structure


import matplotlib.pyplot as plt
import numpy as np import statements Procedural Programming
def calcheat(row,col):
subgrid = b[row-1:row+2,col-1:col+2]
function definitions •  So far we've been applying a procedural
result = 0.1 * (subgrid.sum()+ b[row,col])
return result programming approach
size = 10 •  We've been focusing on the steps of the
b = np.zeros((size,size))
b2 = np.zeros((size,size))
set up variables problem, breaking it down into a sequence of
instructions
for i in range(size):
b[i,0] = 10 input data •  We have control structures to help with the flow
through the sequence
for timestep in range(5):
for r in range(1, size-1): •  When we've found repetition, we've used
for c in range (1, size-1 ):
b2[r,c] =calcheat(r,c)
process data functions (procedures) to factor out that code
for i in range(size):
b2[i,0] = 10 •  Although our code has been procedural, we
b = b2.copy()
have been using Objects…
plt.title('Heat Diffusion Simulation')
plt.imshow(b2, cmap=plt.cm.hot)
output data
... and, in Python, everything's an object
plt.show()
Fundamentals_Lecture10 11 12
Object-Orientation
•  In object-oriented programming, we bundle
the behaviour (methods) and data
(attributes) together
•  Benefits:
•  OO protects data from being used incorrectly
OBJECT ORIENTATION •  Increases code reuse (fewer errors)
Fundamentals of Programming
•  Makes code easier to read and maintain
Lecture 6
•  Objects "know" how to respond to requests
•  Relates to how objects function in the real world
13 Reference: Module 4 of Object-oriented Program Design, Curtin University, 2017 14

Classes – Specifying Objects Encapsulation


•  Before we can use an object, we need to •  A (an object of a) class makes use of the
describe it as a class (of objects). "information hiding" principle
•  Similar to how we define a function once and use •  Communication with the rest of the software system
it multiple times is clearly defined
•  methods are the means for communication
•  The class specifies the state and behaviour •  Its obligations to the software system are clearly
an object can have: defined
•  State: what the object is •  what services the class offers (via data and methods)
•  attributes or member fields •  Implementation details should be hidden from the
•  Behaviour: what the object does user
•  don't need to know how it does things to use it
•  methods or functions
•  stops us "accidentally" changing things and creating errors
15 16
Class Specification Classes and Objects
•  Must include: •  An object is an instance of a class
•  Details of the communication with the rest of the •  The class definition provides a template for
software system (method names) an object
•  The exact data representation required
•  An object gives details for a particular
•  Exactly how the required functionality is to be
instance
achieved (method implementation) Specific cat = instance
Generic cat = class "cat" "Oogie" of class "cat"

17 Fundamentals_Lecture10
http://s460.photobucket.com/user/stefer24/media/scan0024.jpg.html 18

Class roles Class Responsibility


•  Every class is designed with a specific role •  Take the requirements for a software application:
in mind. •  Identify the classes required
•  Assign specific Responsibilities to each class
•  The total set of functional requirements for
•  Determine relationships between classes (see later)
a software system is broken down into a •  Repeat the above steps until the design is correct
set of tasks •  Each responsibility should be handled by that class
•  Collections of tasks are grouped together and no other
•  Example: If a responsibility for keeping track of a person's
and mapped to roles name is assigned to a class called PersonClass then:
•  No other class should have this information
•  Roles are mapped to specific classes
•  Other classes which need this information should refer to this
class when the information is required
19 20
Comparison to non-OO design OO design
•  In a top-down procedural approach, we design •  Before the algorithm is designed:
an algorithm by starting with a main module •  The classes are identified
and using step-wise refinement to determine •  Each class is assigned role(s) or responsibilities

the processing steps •  The required sub modules are designed (i.e.
Constructors, accessors, etc)
•  Some of these steps get refined into sub
•  Each Class is thoroughly tested via a test harness
modules and the process repeats until the
design is refined enough to code •  Finally, the main algorithm and any required
sub modules is designed (making use of the
•  Under Object Orientation this all changes… developed classes in the process)
21 22

Nouns and Verbs Object Communication


•  Like algorithm design, the determination of classes is •  Sometimes referred to as message passing:
still a bit of an art form •  When an object of one class calls an object of another
•  One simple technique is the nouns and verb approach: class it is passing a message (i.e. A request to the
•  Nouns are mapped to classes object to perform some task)
•  Verbs are mapped to sub modules within classes •  The [public] methods must provide the functionality
•  The definition of noun and verb gets stretched to cover required for the class to fulfill its role.
collections of words
•  There are five categories of methods in a class:
•  Result is that:
•  Sub module names should always describe an action (i.e. getName) •  The Constructors
•  Class names should always describe a thing (e.g. PersonClass) •  The Accessor Methods (aka Interrogative Methods)
•  It is important to note that the set of classes proposed •  The Mutator Methods (aka Informative Methods)
will change over the design phase •  Doing Methods (aka Imperative Methods)
•  [Private] methods
23 24
Example: song Song: lumberjack
Classes in Python class Song(): lyrics: ["I'm a lumberjack and
I'm OK", "I sleep all night",
•  Order your code consistently for FOP def __init__(self, lyrics): "And I work all day"]
•  Declare the components of each class in the following self.lyrics = lyrics
order:
def sing_me_a_song(self):
•  Declarations for class constants
for line in self.lyrics:
•  Declarations for class variables/fields print(line)
•  variables which are global to the class
•  Declarations of instance variables (local to each instance) lumberjack = Song(["I'm a lumberjack and I'm OK",
•  Declarations for the Constructors (__init__) "I sleep all night",
"And I work all day"])
•  Accessor methods Python instance and class variables are
•  Mutator methods public, so basic set/gets are not req'd spam = Song(["SPAM, SPAM, SPAM, SPAM",
•  Doing methods ("public") "spam, spam, spam, spam"])
•  Internal methods ("private")
lumberjack.sing_me_a_song()
•  Note that everything in Python is "public" (unlike Java, spam.sing_me_a_song()
C++) so we can only treat methods and data as private
25 https://learnpythonthehardway.org/book/ex40.html 26

BankAccount: bank

Example: dog tricks Dog: d1


Example: bank account interest_rate: 0.3
name: 'Everyday'
class Dog(): number: '007'
name: Brutus class BankAccount ():
balance: 2000
def __init__(self, name): tricks: ["roll over", "sit"] interest_rate = 0.03
self.name = name def __init__(self, name, number, balance):
self.tricks = [] self.name = name
self.number = number
def add_trick(self, trick): self.balance = balance
self.tricks.append(trick)

d1 = Dog('Brutus') bank = BankAccount('Everyday', '007', 2000)


d2 = Dog('Dude')
print("Name: ", bank.name, "\tNumber: ",
d1.add_trick('roll over') bank.number, "\tBalance: ", bank.balance)
d1.add_trick('sit')
d2.add_trick('stay')
d2.add_trick('roll over')
print("Dog's name: ", d1.name, "\nDog's tricks: ", d1.tricks) Output:
print("Dog's name: ", d2.name, "\nDog's tricks: ", d2.tricks)
Name: Everyday Number: 007 Balance: 2000

27 28
Example: bank account Example: bank account (v2)
class BankAccount ():
class BankAccount (): interest_rate = 0.03
def __init__(self, name, number, balance):
interest_rate = 0.03 self.name = name
def __init__(self, name, number, balance): self.number = number
self.name = name self.balance = balance

self.number = number
self.balance = balance accounts = []
bank = BankAccount('Everyday', '007', 2000)
Class variable accounts.append(bank)
bank = BankAccount('Cheque A/C', '008', 3000)
BankAccount: bank accounts.append(bank)
bank = BankAccount('Term Deposit', '009', 20000)
accounts.append(bank)
interest_rate: 0.03
name: 'Everyday' Instance total = 0
number: '007' variables for i in range(len(accounts)):
balance: 2000 print("Name: ", accounts[i].name, "\tNumber: ", accounts[i].number,
"\tBalance: ", accounts[i].balance)
total = total + accounts[i].balance
print("\t\t\t\t\tTotal: ", total)

29 30

Example: bank account (v2) Example: bank account (v3)


class BankAccount (): class BankAccount ():
OUTPUT:
 = 0.3
interest_rate interest_rate = 0.03
def __init__(self,
Name: Everyday name, number, Number:
balance): 007 Balance: 2000 def __init__(self, name, number, balance):
self.name = name self.name = name
Name: Cheque A/C Number: 008 Balance: 3000
self.number = number self.number = number
Name: Term= balance
self.balance Deposit Number: 009 Balance: 20000 self.balance = balance
Total: 25000
def withdraw(self, amount):
accounts = [] self.balance = self.balance - amount
bank = BankAccount('Everyday', '007', 2000)
accounts.append(bank) def deposit(self, amount):
bank = BankAccount('Cheque A/C', '008', 3000) self.balance = self.balance + amount
accounts.append(bank)
bank = BankAccount('Term Deposit', '009', 20000) def add_interest(self):
accounts.append(bank) self.balance += self.balance * self.interest_rate

total = 0 def balances():


for i in range(len(accounts)): total = 0
print("Name: ", accounts[i].name, "\tNumber: ", accounts[i].number, for i in range(len(accounts)):
"\tBalance: ", accounts[i].balance) print("Name:", accounts[i].name, "\tNumber: ", accounts[i].number,
total = total + accounts[i].balance "\tBalance: ", accounts[i].balance)
print("\t\t\t\t\tTotal: ", total) total = total + accounts[i].balance
print("\t\t\t\t\tTotal: ", total)
31 32
Example: bank account (v3)
accounts = []
Self
bank = BankAccount('Everyday', '007', 2000)
accounts.append(bank)
bank = BankAccount('Cheque A/C', '008', 3000) •  Why do I need self when I make __init__ or
accounts.append(bank)
bank = BankAccount('Term Deposit', '009', 20000) other functions for classes?
•  If you don't have self, then code like cheese =
accounts.append(bank)
balances()

print("\nDoing some transactions...\n") 'Gorgonzola' is ambiguous.


•  That code isn't clear about whether you mean
accounts[0].deposit(100)
accounts[1].withdraw(500)
accounts[2].add_interest()
balances() the instance's cheese attribute/variable, or a
local variable named cheese.
•  With self.cheese = 'Gorgonzola' it's very clear
Output:
Name: Everyday Number: 007 Balance: 2000
Name: Cheque A/C
Name: Term Deposit
Number:
Number:
008
009
Balance: 3000
Balance: 20000 you mean the instance attribute self.cheese.
Total: 25000
•  You can use any variable name, but self is the
convention.
Doing some transactions...

Name: Everyday Number: 007 Balance: 2100


Name: Cheque A/C Number: 008 Balance: 2500
Name: Term Deposit Number: 009 Balance: 20600.0
Fundamentals_Lecture10 Total: 25200.0 33 https://learnpythonthehardway.org/book/ex40.html 34

OO Design…Where to begin? Test our objects out…


•  Find your objects CAT

•  If we wanted to keep track of our household Name: Oogie


animals: cats, dogs and birds DOB: 1/1/2006
DOG
Colour: Grey
•  We could make classes for cats, dogs and Breed: Fluffy
Name: Dude
birds DOB: 1/1/2011
Colour: Brown
•  For each animal, we might track: Breed: Jack Russell
BIRD
•  name
•  date of birth Name: Big Bird
DOB: 10/11/1969
•  colour Colour: Yellow
Breed: Canary
•  breed

35 36
animals.py - Dog Class (v2) animals.py - Cat Class
class Dog(): class Cat():

myclass = "Dog" myclass = "Cat"

def __init__(self, name, dob, colour, breed): def __init__(self, name, dob, colour, breed):
self.name = name self.name = name
self.dob = dob self.dob = dob
self.colour = colour self.colour = colour
self.breed = breed self.breed = breed

def printit(self): def printit(self):


print('Name: ', self.name) print('Name: ', self.name)
print('DOB: ', self.dob) print('DOB: ', self.dob)
print('Colour: ', self.colour) print('Colour: ', self.colour)
print('Breed: ', self.breed) print('Breed: ', self.breed)
print('Class: ', self.myclass) print('Class: ', self.myclass)

37 Fundamentals_Lecture10 38

animals.py - Bird Class Pets.py Or…

from animals import *


class Bird(): from animals import Dog
from animals import Cat
myclass = "Bird" from animals import Bird

def __init__(self, name, dob, colour, breed): dude = Dog('Dude', '1/1/2011', 'Brown', 'Jack Russell')
self.name = name oogs = Cat('Oogie', '1/1/2006', 'Grey', 'Fluffy')
self.dob = dob bbird = Bird('Big Bird', '10/11/1969', 'Yellow', 'Canary')
self.colour = colour
self.breed = breed dude.printit()
oogs.printit()
def printit(self): bbird.printit()
print('Name: ', self.name)
print('DOB: ', self.dob)
print('Colour: ', self.colour)
print('Breed: ', self.breed)
print('Class: ', self.myclass)

39 40
Pets.py Name: Dude Summary
DOB: 1/1/2011
from animals import Dog Colour: Brown
from animals import Cat Breed: Jack Russell •  Understand the main concepts in object-
Class: Dog
from animals import Bird
oriented programming and their value
dude = Dog('Dude', '1/1/2011', 'Brown', Name:
'Jack Oogie
•  Read and explain object-oriented code
Russell')
oogs = Cat('Oogie', '1/1/2006', 'Grey', DOB: 1/1/2006
'Fluffy')
Colour: Grey'Canary')
bbird = Bird('Big Bird', '10/11/1969', 'Yellow',
Breed: Fluffy •  Apply and create simple object-oriented
Class: Cat
dude.printit()
oogs.printit() Python code
bbird.printit() Name: Big Bird
DOB: 10/11/1969
Colour: Yellow
Breed: Canary
Class: Bird
If you try to print dude directly:


animals.Dog object at 0x10108d978
41 42

Practical Sessions Assessments


•  We'll be coding objects and using them •  We've sat Prac Test 2 in the week
preceding this lecture

•  We have an in-class written test next week


during the lecture
•  The assignment will be released later this
week

43 44
Mid-semester Test Why did you show the previous slide?
•  60 minutes + 5 minutes reading time •  The mid-semester test was important
•  Covers weeks 1-6 of lectures, weeks 1-5 of •  Motivation to revise the course so far
•  Feedback on how well you understand the unit
practicals •  Invigilated – so we know it's your work
•  i.e. just simple questions from OO
•  It was dropped because we were forced to reduce
•  Questions based on lectures, practicals, practical
the number of assessments
tests, revision questions and review questions •  The practical tests and assignment were
•  Examples are available on Blackboard considered more important
•  The past papers are an excellent resource for you
•  Hopefully will have a ComSSA revision TBA to review your knowledge
•  Make use of Piazza and practical sessions to get
feedback
45 46

Next week…

•  Test during lecture – 22/9/19


•  If you have a Curtin Access Plan, and haven't
informed me, do so ASAP.

•  Lecture 7:
•  Relationships in Object-orientation
•  Exception handling

47

You might also like