0% found this document useful (0 votes)
5 views25 pages

Object-Oriented Programming in Python

The document outlines an introductory module on Object-Oriented Programming (OOP) at the University of Greenwich, focusing on examples such as a Home Hub, Uni App, and Pizza ordering system. It provides suggested textbooks for further reading, details on using PyCharm for coding, and discusses the structure and organization of example projects. The rationale for OOP is presented, emphasizing its advantages in managing complex data and functionalities compared to traditional list-based approaches.
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)
5 views25 pages

Object-Oriented Programming in Python

The document outlines an introductory module on Object-Oriented Programming (OOP) at the University of Greenwich, focusing on examples such as a Home Hub, Uni App, and Pizza ordering system. It provides suggested textbooks for further reading, details on using PyCharm for coding, and discusses the structure and organization of example projects. The rationale for OOP is presented, emphasizing its advantages in managing complex data and functionalities compared to traditional list-based approaches.
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

Object-Oriented Programming:

Introduction
Chris Walshaw
Computing & Mathematical Sciences
University of Greenwich

1
Objectives

• Introduction to module
- suggested textbooks
- extended examples
- code organisation
• Home hub example
- basic internet of things simulation
• Uni app example
- basic messaging app simulation
• Pizza example
- basic online ordering/e-commerce simulation
2
Suggested Textbooks
• If you want a textbook to read, you could
try one of these
- Python Crash Course (2e): A Hands-On,
Project-Based Introduction to Programming,
Eric Matthes, No Starch Press
- Think Python: How to think like a Computer
Scientist (2e), Allen Downey, O’Reilly
• downloadable pdf available for free(!) at
[Link]
- A Concise Introduction to Programming in
Python, Mark Johnson, CRC Press
• All 3 books are a good introduction to
object-oriented programming in Python
and go beyond what we cover

3
Motivation – examples
• We will be working on 3 extended examples through
the module with different (better & better) versions
each week
- Home Hub – a simulation of something like Google Nest or
Amazon Echo … but without the voice activation or the
physical devices
- Uni App – a simulation of a basic University app for
broadcasting messages to groups of users … but without the
actual messaging
- Python Pizzas – a simulation of a pizza ordering app … but
without any actual pizzas 
• the initial versions of the app just generate random pizzas
• The first set of examples use familiar techniques from
Programming Foundations
- e.g. conditionals, functions, lists, loops
- we will review them as revision

4
Example organisation
• Each example generally consists of a folder containing
several python files
• Python only has fairly basic modularisation
possibilities when importing code from other files
- so if you have two files named [Link] in two different
folders, you are never certain which will get picked
• To avoid any issues all the files & folders are
numbered ([Link], [Link], etc)
- then “import pizza02 as pz” is unambiguous
- the numbering matches the folder name – so [Link] is in
the folder Pizza03
- however in many cases, files in different folders may be the
same as each other
• Also each folder is completely self-contained
- code in one folder does not use code from another folder

5
PyCharm

• We shall be working with PyCharm


- you can download and install the community
edition for free for your own computer at home
• PyCharm is developed by JetBrains
- also provide IntelliJ (Java), DataGrip for
databases / SQL and various .NET plug-ins
- [Link]
• Available for Windows / Mac / Linux
machines
6
PyCharm installation

• Download from [Link]


- make sure you download the Community
edition (free), not the Professional (free trial)
• Stick to the standard installation
- don’t associate .py files with
PyCharm (you can change
later if you wish)

7
PyCharm settings

• Don’t import settings


- unless you are already a PyCharm user

• You should get a start up screen like this

8
Opening the examples

• Each week, the download file is set up as


a PyCharm project
• So you need to download it, UNZIP IT,
and open it with PyCharm (File > Open)

9
Running a program
• First open a program
- let’s work with [Link] from Hub01 in this week’s
examples
- browse to it in the Files window and double click
• You can run a single file like this in several ways
- from the menu “Run > Run controller01”
- right-click on the file in the file browser or the code editor
and select “Run controller01”
- Ctrl+Shift+F10, or, if you have run it previously,
Shift+F10 or the button, top right
• Make sure you type your input in the Run window
(at the bottom) and not in the code editor!!!
- DEMO

10
Windows Firewall

• The first time you run it you may see a


dialog from the Windows Firewall

• Click “Allow access”


11
Home hub
• The idea of the Home hub examples is to simulate the
interaction between a hub and its connected smart
devices
- e.g. lights, heating, music player, etc
- sometimes known as the “internet of things”
• In real-life the software would also require
- a voice recognition module … to convert speech to text
- a set of independent devices connected via bluetooth / wifi
• Although our simulation has neither it is a nice
example to demonstrate multiple object-oriented
techniques
- classes, objects, GUIs, encapsulation, methods, abstraction,
polymorphism … more later!
• We start with a simple “controller” with 3 “devices” and
a control loop
12
Hub01 – lists

• The first example is managed by 4 lists


for example …
device_names = ["heating", "ceiling light", "music player"]
device_ons = [False, False, False]
device_types = ["temperature", "brightness", "volume"]
the heating …
device_settings = [18, 350, 7]
… is not on yet …
for device in device_names:
print(f"{device} has been initialised") … but when it’s
name = input("What is your name? ") switched on, the
print(f"Hello {name}")
temperature …
while True:
# this is the main control loop … will be 18⁰C
...

print(f"Bye bye, {name}")

13
Hub01 – device chosen
• Main control loop
- the user inputs a command (by typing rather than speaking)
- the control loop tries to figure out which device is chosen
def chosen(device, command):
if device in command or
should recognise “music player on”
[Link](" ", "") in command:
return True
else: … or “musicplayer on”
return False

while True:
prompt user for a command &
print()
command = input(f"What next, {name}? ")
convert to lower case
command = f" {[Link]()} "
exit the loop on “system off”
if "system off" in command:
break

device_chosen = None
loop over the device names
for device in device_names:
if chosen(device, command):
check if each is mentioned in
device_chosen = device
break
the command
14
Hub01 – commands
• The if / elif block recognises “on”, “off”, “up” &
“down” and “play” & “pause” for the music player
if device_chosen is None:
print(f"Sorry {name}, I do not understand that")
else:
i = device_names.index(device)
if " on " in command:
device_ons[i] = True
print(device + " is on")
elif " off " in command:
device_ons[i] = False
print(device + " is off")
elif " up " in command:
device_settings[i] += 1
print(f" {device} {device_types[i]} is set to {device_settings[i]}")
elif " down " in command:
device_settings[i] -= 1
print(f" {device} {device_types[i]} is set to {device_settings[i]}")
elif " play " in command and device == "music player":
print(f" {device} is playing")
elif " pause " in command and device == "music player":
print(f" {device} is paused")
else:
print(f"Sorry {name}, I do not understand that")
15
Hub 01 – example output
heating has been initialised
ceiling light has been initialised
music player has been initialised

What is your name? Chris


Hello Chris

What next, Chris? heating on


heating is on

What next, Chris? heating up


heating temperature is set to 19
need to give the full
What next, Chris? music play
Sorry Chris, I do not understand that
name of each device
What next, Chris? music player on
music player is on

What next, Chris? music player play


music player is playing

What next, Chris? system off


Bye bye, Chris

16
UniApp01 – lists

• The first version of Uni app is also managed


by 3 lists, defined in [Link]
def get_names(): def get_user_ids(): def get_infos():
guest = "Alice" guest = None guest = None # guest user
admin = "Bobby" admin = "bob01 admin = None # administrator
staff1 = "Chris" staff1 = "chr02" staff1 = "Lecturer"
staff2 = "Diana" staff2 = "dia03" staff2 = "Professor"
student1 = "Eddie" student1 = "edd04" student1 = "BSc Computing"
student2 = "Frank" student2 = "fra05" student2 = "BSc Computer Science"
student3 = "Gerri" student3 = "ger06" student3 = "MSc Data Science"

names = [guest, user_ids = [guest, details = [guest,


admin, staff1, admin, staff1, admin, staff1,
staff2, student1, staff2, student1, staff2, student1,
student2, student3] student2, student3] student2, student3]
return names return user_ids return details

not everyone has a not everyone has a job


user id title / degree programme
17
UniApp01 – initialisation

• Initially the app gets the user details from


the database and prints them out
import database01 as db

names = db.get_names()
user_ids = db.get_user_ids()
infos = db.get_infos()

# print out all the user details


for i in range(len(names)):
name = names[i]
user_id = user_ids[i]
use the info to figure out if
info = infos[i]
print(f"name: {name}")
the person is a student,
if user_id is not None:
print(f"user id: {user_id}")
member of staff or neither
if info is not None:
if [Link]("BSc") or [Link]("MSc "): # this is a student
print(f"programme: {info}")
else: # this is a member of staff
print(f"job title: {info}")
print()

18
UniApp01 – main loop
• The main loop repeatedly asks the user for a group
(staff, students or all) and a message and “sends” the
message to the group
while True:
group = input("Group (staff, students or all)? ")
if group == "":
break
message = input("Message? ")
if the group, or the message
if message == "":
break
is empty the loop terminates
for i in range(len(names)):
info = infos[i]
send_message = False
loop over the users to see if
if group == "all":
send_message = True
they are in the chosen group
elif info is not None:
is_student = [Link]("BSc ") or [Link]("MSc ")
if group == "students" and is_student:
send_message = True
if group == "staff" and not is_student:
send_message = True
if send_message:
name = names[i] if they are, “send” the
print(f" '{message}' sent to {name}")
message 19
UniApp01 – example
output
name: Alice Group (staff, students or all)? students
Message? Hello and welcome
name: Bobby 'Hello and welcome' sent to Eddie
user id: bob01 'Hello and welcome' sent to Frank
'Hello and welcome' sent to Gerri
name: Chris Group (staff, students or all)? staff
user id: chr02 Message? Good luck
job title: Lecturer 'Good luck' sent to Chris
'Good luck' sent to Diana
name: Diana Group (staff, students or all)? all
user id: dia03 Message? Well done
job title: Professor 'Well done' sent to Alice
'Well done' sent to Bobby
name: Eddie 'Well done' sent to Chris
user id: edd04 'Well done' sent to Diana
programme: BSc Computing 'Well done' sent to Eddie
'Well done' sent to Frank
name: Frank 'Well done' sent to Gerri
user id: fra05 Group (staff, students or all)?
programme: BSc Computer Science

name: Gerri
user id: ger06 output from main loop
programme: MSc Data Science
initial list of users
20
Pizza01 – lists

• Again the first version uses lists to store the


data (pizzas/toppings and their prices)
- then generates a random pizza with 1-3 toppings
from random import randint

def get_random_index(items):
return randint(0, len(items) - 1)

pizza_types = ["margherita", "napoletana", "marinara"]


pizza_prices = [6.0, 7.0, 7.5]
extra_types = ["mushrooms", "cheese", "anchovies", "sausage"]
extra_prices = [0.5, 1.0, 1.5, 1.8]

random = get_random_index(pizza_types)
pizza_type = pizza_types[random] uses get_random_index()
pizza_price = pizza_prices[random]
to pick a random number
between 0 and 2
21
Pizza01 – random toppings

pizza_description = pizza_type
picks a random number of
n_random_extras = randint(1, 3) extras between 1 & 3
for i in range(n_random_extras):
random = get_random_index(extra_types)
extra_type = extra_types[random]
if i == 0:
picks the extras at random
pizza_description += f" with extra {extra_type}"
else:
pizza_description += f", {extra_type}"generates the description
extra_price = extra_prices[random]
pizza_price += extra_price and calculates the price
print(f"You have won a {pizza_description} worth £{pizza_price:.2f}")

prints description & price

22
Pizza01 – example output

You have won a margherita with extra cheese, sausage, anchovies worth £10.30

each run just generates one pizza


You have won a napoletana with extra sausage worth £8.80

You have won a marinara with extra cheese, cheese worth £9.50

but because of the way the code is


written you might get the same
topping 2 or even 3 times

23
Object-oriented
programming rationale
• All three examples work, but none is ideal
• Generally the data is stored in lists
- the lists all need to be the same length
- sometimes the lists store redundant information (so user_id is set to None for
guest users)
• None of the apps are very flexible
- for example, in the Home Hub, how would we cope with a variety devices that
have lots of different functionalities (on/off, up/down, play/pause, start
time/end time, motion detection, …)
• The ideas behind object-oriented programming allow us to model a
variety of different, but sometimes similar, things in code
- often this has to do with grouping data and functionalities together rather than
separating them into lots of lists
- e.g. the heating needs to know about on/off, temperature settings and
start/end times …
- … but the music player needs to know about on/off, volume settings and
play/pause

24
Summary

• Introduction to module
- suggested textbooks
- extended examples
- code organisation
• Home hub example
- basic internet of things simulation
• Uni app example
- basic messaging app simulation
• Pizza example
- basic online ordering/e-commerce simulation
25

You might also like