Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

SFWRTECH 3RQ3 - Introduction To Object Oriented Programming: Sean Watson

This document provides an introduction to object oriented programming concepts using Python. It discusses installing Python and related packages, defines a simple GreetingPrinter class with a name attribute and print_name method, and explains how this implements the corresponding class diagram. The document emphasizes that object oriented design focuses on modeling real-world objects and their relationships in code.

Uploaded by

sadawad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

SFWRTECH 3RQ3 - Introduction To Object Oriented Programming: Sean Watson

This document provides an introduction to object oriented programming concepts using Python. It discusses installing Python and related packages, defines a simple GreetingPrinter class with a name attribute and print_name method, and explains how this implements the corresponding class diagram. The document emphasizes that object oriented design focuses on modeling real-world objects and their relationships in code.

Uploaded by

sadawad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

SFWRTECH 3RQ3 – Introduction to Object Oriented

Programming

Sean Watson

November 18, 2021

Sean Watson Intro to OOP November 18, 2021 1 / 31


1 Installation and Setup

2 Getting Started

3 Object Orientation
Has Relationships
Is Relationships

4 Summary

Sean Watson Intro to OOP November 18, 2021 2 / 31


Installation and Setup

Install
Find the latest stable version of Python(3.10.0 as of this writing)
from https://python.org.
Follow the installation instructions for your operating system.
Verify your install with the command python --version or
python3 --version

Note: Both Mac OS and most Linux distros include some version of
Python, make sure you have a modern version(3.6+) and not 2.x

Sean Watson Intro to OOP November 18, 2021 3 / 31


Installation and Setup

Package Installer
Your Python install should have given you access to pip
This tool allows for installing Python packages from the command
line
We will want to use it to install PyTest with the following command:
python -m pip install pytest
Alternative: you may be able to install directly into your IDE
Python has decent ‘out of the box’ testing, but PyTest is an
excellent add-on to write clearer, more concise tests

Sean Watson Intro to OOP November 18, 2021 4 / 31


Installation and Setup

IDE Install
In class demos will be in PyCharm, which can be downloaded from
https://jetbrains.com/pycharm/
If you prefer, VS Code is another good choice and can be downloaded
from https://code.visualstudio.com/(requires a Python
extension installed)
We will only be using plain, vanilla Python in exercises, do not worry
about any extra libraries that get mentioned

Slight advantage of PyCharm is that it will set up a skeleton project for


you and set a virtual environment Setting up a virtual environment to be
used with VS Code is not difficult, and you will find many online tutorials

Sean Watson Intro to OOP November 18, 2021 5 / 31


Getting Started

Let’s take a peek at what PyCharm automatically builds for us


1 def print_hi ( name ) :
2 # Print this message to the console
3 print ( f ’Hi , { name } ’)
4
5 # Check if we are in the main
6 if __name__ == ’ __main__ ’:
7 print_hi ( ’ class of 3 RQ3 ’)

OK, nice to have some code that runs


The output here will be the printed string Hi, class of 3RQ3
Let’s try to figure out some more details

Sean Watson Intro to OOP November 18, 2021 6 / 31


Getting Started

First off, the # indicates a comment, these won’t run


By default Python will just run whatever we have written down
No boilerplate code is needed to mark the beginning of a program
Note that the two points above are part of why Python is called a
scripting language
We would get the exact same output if we ran the following code:

print(’Hi, class of 3RQ3’)

Why? This is the first executable line in our file


Python will just look for something it can execute and do it

Sean Watson Intro to OOP November 18, 2021 7 / 31


Getting Started

So what’s the other stuff for then?


In our original file the first executable line is this one:

if __name__ == ’__main__’:

This is a bit funny looking, and quite specific to Python


The variable __name__ is set automatically by Python for you
I If you run this file specifically, its name is ’__main__’
I If you run some other file, which calls this file it will be named its file
name, say ’3rq3example’

Sean Watson Intro to OOP November 18, 2021 8 / 31


Getting Started

When we run our program then, __name__ == ’__main__’ will be true


Notice that this line ends with a colon, why is that?
I Most languages wrap an if with { ... } to show what happens when
the condition is true
I Python doesn’t like squiggly brackets, so it indents instead
I This is referred to as the offside rule
So, the colon means that the next indented block relies on this
statement

Sean Watson Intro to OOP November 18, 2021 9 / 31


1 # which lines run when the condition is true
2 # and which ones when it is false ? why ?
3
4 if __name__ == ’ __main__ ’:
5 print ( ’Hi , class of 3 RQ3 ’)
6 print ( ’I always run ’)
7

Sean Watson Intro to OOP November 18, 2021 10 / 31


Getting Started

Now we know why the if statement gets true and why the next line
runs
But what about all that def stuff up at the top of our file?
1 def print_hi ( name ) :
2 print ( f ’Hi , { name } ’)
3

First point is that def is short for define


So what are we doing here? Defining a new method called print_hi
I It has one input parameter called name
I How do we know which lines are part of this method?

Sean Watson Intro to OOP November 18, 2021 11 / 31


Getting Started

A quick aside about print()


Programmers among us will be very familiar with this idea
It just takes some text and prints it to the console
I If we run in PyCharm, we will see the output in the PyCharm console
I If we run in the command line, we will see the output there
A way to make your program communicate with the outside world

Sean Watson Intro to OOP November 18, 2021 12 / 31


Getting Started

Let’s take a second look at our original file and figure out what it
does and why:
1 def print_hi ( name ) :
2 # Print this message to the console
3 print ( f ’Hi , { name } ’)
4
5 # Check if we are in the main
6 if __name__ == ’ __main__ ’:
7 print_hi ( ’ class of 3 RQ3 ’)

1 Defines a new method with one parameter we can call at any time
2 Checks to see if the __name__ variable is what we expect
3 If it is, it calls our print_hi method, which prints a string
4 If it is not, it calls nothing and just ends

Sean Watson Intro to OOP November 18, 2021 13 / 31


Getting Started

Some notable points for Java/C#/C++ experts


I Notice that parameters do not have types
F Types are dynamically determined at run time
I Notice that methods do not have explicit return values
F Again, it is dynamically determined if a method returns something or
nothing
I White space for indentation is critical to correct running of the program
I Python supports (as we will see), but does not require classes
I Intention is to ‘look like’ pseudo code for fast prototyping

Sean Watson Intro to OOP November 18, 2021 14 / 31


Object Orientation

Now we know the basics, let’s figure out how to make something
Object Oriented
To do this, we need to define what we mean
I We talked about objects in the last lecture, so we are familiar with this
I A programmed object implements the specification given by the
diagram
I We need all the attributes, behaviours and relationships of our class
diagram

Sean Watson Intro to OOP November 18, 2021 15 / 31


Object Orientation

We understand objects because we’ve already seen them, but what


about being object oriented
Effectively, we make the objects first class
I Our overall design is decided by our collection of objects
I All decisions are led by our objects
I How will a new method be implemented?
F Determine which objects are involved
F Determine which objects are affected
F Determine which objects may need to listen

Sean Watson Intro to OOP November 18, 2021 16 / 31


Object Orientation

Our class diagram is the most critically important diagram


It shows the structure of our objects and their relationships
Conceptually this is a simple paradigm
I Relation to real world objects makes relationships simpler to visualize
I Domain knowledge can immediately translate into program knowledge
I Makes finding relevant behaviour easier

Sean Watson Intro to OOP November 18, 2021 17 / 31


Object Orientation

This means that we need to meet the class construct in Python


1 class GreetingPrinter :
2 """ This is a class for storing and printing
someone ’s name """
3 name = ’ class of 3 RQ3 ’
4
5 def print_name () :
6 print ( f ’Hi , { name } ’)

This class has one attribute


It also has one method

Sean Watson Intro to OOP November 18, 2021 18 / 31


Object Orientation

Our class, therefore, matches up with the following class diagram:

In other words, we have implemented one attribute for representing


someone’s name, and a method of printing it

Sean Watson Intro to OOP November 18, 2021 19 / 31


Object Orientation

Let’s go through line by line to see what is going on here


class means that we are defining a self-contained object
I This is different than def which says we’re implementing a method
I A class may contain many methods, and many attributes
GreetingPrinter is the class name, convention puts this in
PascalCase
The words enclosed by """ create a docstring or description of the
class
The rest of this code we’ve already met

Sean Watson Intro to OOP November 18, 2021 20 / 31


Object Orientation

A bit of an issue with our syntax here


1 from class import GreetingPrinter
2
3 printer = GreetingPrinter ()
4 printer . print_name ()
5
6 printer2 = GreetingPrinter ()
7 printer2 . name = ’ Sean ’
8 printer2 . print_name ()
9 # prints " Hi , Sean "
10
11 printer . print_name ()
12 # what does this print ?

Sean Watson Intro to OOP November 18, 2021 21 / 31


Object Orientation

What went wrong here?


Our variable name is owned by the class and not the object
I The class is the blueprint from which individual objects can be built
I If all objects will have something in common, then it goes on the class
F All items will have a method called print_name
F All items may have some shared data (perhaps a filename for logging)
I However, each object will probably need to have its own name
I Thefore, the name should be owned by an object and not by a class

Sean Watson Intro to OOP November 18, 2021 22 / 31


Object Orientation

Meet self
1 class GreetingPrinter :
2 """ This is a class for storing and printing
someone ’s name """
3 def __init__ ( self , name ) :
4 self . name = name
5
6 def print_name ( self ) :
7 print ( f ’Hi , { self . name } ’)

__init__ is short for initialize, it is responsible for building our objects

Sean Watson Intro to OOP November 18, 2021 23 / 31


Object Orientation

1 from class import GreetingPrinter


2
3 printer = GreetingPrinter ()
4 printer . print_name ()
5
6 printer2 = GreetingPrinter ()
7 printer2 . name = ’ Sean ’
8 printer2 . print_name ()
9 # prints " Hi , Sean "
10
11 printer . print_name ()
12 # what does this print ?

Sean Watson Intro to OOP November 18, 2021 24 / 31


Object Orientation

Has a relationships
Remember that in a has a relationship, we are discussing a
component of an object
I Menu has Menu Items
What does this remind us of?
I Attributes!
I An attribute doesn’t need to be a simple type like a number or string,
it can also be another object

Sean Watson Intro to OOP November 18, 2021 25 / 31


Object Orientation

1 class MenuItem :
2 """ This represents a selectable item from the
menu """
3 def __init__ ( self , name , category , price ) :
4 self . name = name
5 self . category = category
6 self . price = price
7

1 class Menu :
2 """ This represents a restaurant menu """
3 def __init__ ( self , items ) :
4 self . items = items
5
6 def g et _ a ll_by_category ( self , category ) :
7 return [ item for item in items if item .
category == category ]
8

Sean Watson Intro to OOP November 18, 2021 26 / 31


Object Orientation

So, our class Menu contains many items which are of type MenuItem
This follows from our earlier statement that Menu has MenuItems
So we can see then, that has a relationships can be modeled as
attributes
I The “owning” object, contains an attribute with the type of the
“contained” object
I These can be cases where we have exactly one, one-to-many or
zero-to-many relationships

Sean Watson Intro to OOP November 18, 2021 27 / 31


Object Orientation

Is a relationships
Remember that in this case one object is a special case of another
A daily special is definitely a menu item
I It needs to have the same information as a regular menu item
I However, it may have some extra attributes or may have different
methods
I So we say that the new class inherits the old class, and adds to it

Sean Watson Intro to OOP November 18, 2021 28 / 31


Object Orientation

1 class MenuItem :
2 """ This represents a selectable item from the
menu """
3 def __init__ ( self , name , category , price ) :
4 self . name = name
5 self . category = category
6 self . price = price
7

1 class DailySpecial ( MenuItem ) :


2 """ This represents the daily special , a
special item from the menu """
3 def __init__ ( self , name , category , price ,
discount ) :
4 MenuItem . __init__ ( name , category , price )
5 self . discount = discount
6

Sean Watson Intro to OOP November 18, 2021 29 / 31


Object Orientation

Now, consider that our Menu contains MenuItems, can some of these
be DailySpecials?
I Yes!
I We say that the signature of the subclass(DailySpecial) extends that
of the superclass(MenuItem)
I This means that we are guaranteed to find at least the properties of
the superclass
I We won’t look for more specific items, so it doesn’t matter what the
subclass adds
This relationship is a major part of OOP, and something we always
need to be on the lookout for
I It can potentially save us tons of extra coding and potential errors by
stopping us from writing the same code twice

Sean Watson Intro to OOP November 18, 2021 30 / 31


Summary

We’ve got started with Python in PyCharm


Taken a close look at a default Python project
What does object oriented code mean to us?
I For the purposes of this course, it means that we build code to the
specs of the class diagram
I Viewed some examples in Python
Went through translating some class diagrams from last lecture into
Python classes

Sean Watson Intro to OOP November 18, 2021 31 / 31

You might also like