SlideShare a Scribd company logo
CSIT121
Object-Oriented Design and
Programming
Dr. Fenghui Ren
School of Computing and Information Technology
University of Wollongong
1
Lecture 4 outline
• Modules and packages
• Third-party libraries
• Test-driven development
• Unittest module
• Code coverage
2
Modules
• For small programs, we can put all our classes into one file and add a
little script at the end to start them interacting.
• For large programs, it can become difficult to find the one class that
needs to be edited among the many classes we’ve defined.
• We need to use modules.
• Modules are simply Python files. One Python file equals one module.
• If we have multiple modules with different class definitions, we can
load classes from one module to reuse them in the other modules.
E.g. put all classes and functions related to the database access into
the module ‘database.py’.
Modules
• The ‘import’ statement is used for importing modules or specific classes or
functions from modules. E.g. we used the import statement to get Python’s
built-in math module and use its sqrt function in the distance calculation
Suppose we have:
• A module called ‘database.py’ which contains a Database class
• A second module called ‘products.py’ which responsible for product-
related queries.
• ‘products.py’ needs to instantiate the Database class from
‘database.py’
module so that it can execute queries on the product table in the
database.
• We need import Database class in the products module.
Modules
• To import the whole database module into the products namespace
so any class or function in the database module can be accessed using
the ‘database.<something>’ notation.
Import database
db = database.Database()
# Do queries on db
Modules
• To import just one class (Database class) from the database module
into the products namespace so all the class functions can be
accessed directly.
from database import Database
db = Database()
# Do queries on db
Modules
• If the products module already has a class called Database, and we
don’t want the two names to be confused, we can rename the
imported class when used inside the products module
from database import Database as DB
db_product = Database()
Db_database = DB()
# Do queries on db
Modules
• We can also import multiple classes in one statement. If our database
module also contains a Query class, we can import both classes as
follows.
from database import Database, Query
db = Database()
query = Query()
# Do queries on db via query
Modules
• Don’t do this
from database import *
Because,
• You will never know when classes will be used
• Not easy to check the class details (using help()) and maintain
your program
• Unexpected classes and functions will be imported. For example, it will also
import any classes or modules that were themselves imported into that
file.
Modules
• For fun, try typing ‘import this’ in your interactive interpreter. You will
get a poem about Python philosophy. 
Package
• As a project grows into a collection of more and more modules, it is better
to add another level of abstract.
• As modules equal files, one straightforward solution is to organise files
with folders (called packages).
• A package is a collection of modules in a folder. The name of the package is
the name of the folder.
• We need to tell Python that a folder is a package to distinguish it from
other folders in the directory.
• We need to place a special file in the package folder named ‘ init
.py’.
• If we forget this file, we won’t be able to import modules from that
folder.
Package
• Put our modules inside an
ecommerce directory in our
working folder (parent_directory)
• The working folder also contains a
main.py module to start the
program.
• We can add another payment
directory inside the ecommerce
directory for various payment
options.
• The folder hierarchy will look like
this.
Package
In Python 3, there are two ways of importing modules from a package:
absolute imports and relative imports.
• Absolut imports specify the complete path to the module in the
package, functions, or classes we want to import
• Relative imports find a class, function, or module as it is positioned
relative to the current module in the package.
Package
Absolute imports
• If we need access to the Product class inside the products module, we
could use any of these syntaxes to perform an absolute import.
Package
Absolute imports
Which way is better? It depends.
• The first way is normally used if you have
some kind of name conflict from multiple
modules. You have to specify the whole
path before the function calls.
• If you only need to import one or two
classes, you can use the second way. Easy
to call functions.
• If there are dozens of classes and
functions inside the module that you
want to use, you can import the module
using the third way.
Package
Relative imports
• If we are working in the products module and
we want to import the Database class from the
database module next to it, we could use a
relative import.
from .database import Database
• The period ‘.’ in front of the database says
‘using the database module inside the current
package’.
• The current package refers to the package
containing the module (products.py) we are
currently working in, i.e., the ecommerce
package.
Package
Relative imports
• If we were editing the square.py module inside
the payments package, we want to use the
database package inside the parent package.
from ..database import Database
• We use more periods to go further up the
hierarchy.
• If we had an ecommerce.contact package
containing an email module and wanted to
import the send_mail function.
from ..contact.email import send_mail
Inside a module
• We specify variables, classes or functions inside modules.
• They can be a handy way to shore the global state without
namespace conflicts.
• For example, it might make more sense to have only one database
object globally available from the database module.
• The database module might look like this:
Inside a module
• Then we can use any of the import methods we’ve discussed to
access the database object, such as
• In some situations, it may be better to create objects until it is
actually needed to avoid unnecessary delay in the program.
Inside a module
• All module-level code is executed immediately at the time it is
imported.
• However, the internal code of functions will not be executed until
the function is called.
• To simplify the process, we should always put our start-up code in a
function (conventionally called ‘main’) and only execute that function
when we know we are running the module as a script, but not when
our code is being imported from a different script.
• We can do this by guarding the call to ‘main’ inside a conditional
statement.
Inside a module
Important note: Make it a policy to wrap all your scripts in an ‘if name == “ main ”:’
your_testing_code’ pattern in case you write a function that you may want to be imported by
other code at some point in the future.
Third-party libraries
• You can find third-party libraries on the Python Package Index (PyPI) at
http://pypi.python.org/. Then you can install the libraries with a tool
called ‘pip’
• However, ‘pip’ is not pre-installed in Python, please follow the
instructions to download and install ‘pip’: http://pip.readthedocs.org/
• For Python 3.4 and higher, you can use a built-in tool called ‘ensurepip’
by installing it with the command ‘$python3 –m ensurepip’
• Then, you can install libraries via the command ‘$pip install
<library_name>’
• Then the third-party library will be installed directly into your system
Python directory.
Third-party libraries
We will learn Matplotlib (a low-level graph plotting library) in this subject.
Program Testing
Why test?
• To ensure that the code is working the way the developer thinks it should
• To ensure that the code continues working when we make changes
• To ensure that the developer understood the requirements
• To ensure that the code we are writing has a maintainable interface
Test-driven development methdology
Principle
• Write tests for a segment of code first
• Test your code (it will fail because you don’t write the code yet)
• Write your code and ensure the test passes
• Write another test for the next segment of your code
• Write your code and ensure the test passes
…
It is fun. You build a puzzle for yourself first, then you solve it!
Test-driven development methodology
The test-driven development methodology
• ensures that tests really get written;
• forces us to consider exactly how the code will be used.
• It tells us what methods objects need to have and how attributes will
be accessed;
• helps us break up the initial problem into smaller, testable problems,
and then to recombine the tested solutions into larger, also tested,
solutions;
• helps us to discover anomalies in the design that force us to consider
new aspects of the software;
• will not leave the testing job to the program users.
Unit Test
• Same as Java, Python also has a built-in test library called ‘unittest’
• ‘unittest’ provides several tools for creating and running unit tests.
• The most important one is the ‘TestCase’ class.
• ‘TestCase’ class provides a set of methods that allow us to compare
values, set up tests, and clean up when the tests have finished.
Unit Test
• Create a subclass of TestCase (we will introduce the inheritance next
lecture) and write individual methods to do the actual testing.
• These method names must all start with the prefix ‘test’.
• TestCase class will automatically run all the test methods and report
the test results
Unit Test
• Pass the test
Unit Test
• fail the test
Unit Test
• more tests
Unit Test
• Assert methods
Reducing boilerplate and cleaning up
• No need to write the
same setup code
for each test
method if the test
cases are the
same.
• We can use the
‘setUp()’ method on
the TestCase class to
perform initialisation
for test methods.
Organise your test classes
• We should divide our test classes into modules and packages (keep
them organized)
• Python’s discover module (‘python3 –m unittest’) can find any
TestCase objects in modules if your tests module starts with the
keyword ‘test’.
• Most Python programmers also choose to put their tests in a
separate
package (usually named ‘tests/’ alongside their source
directory).
Object oriented programming design and implementation
Ignoring broken tests
• Sometimes, a test is known to fail, but we don’t want to report the
failure.
• Python provides a few decorators to mark tests that are expected to
fail or to be skipped under known conditions.
• ‘@expectedFailure’, ‘@skip(reason)’, ‘@skipIf(condition, reason)’,
‘@skipUnless(condition, reason)’
Ignoring broken tests
Tests results:
• The first test fails and is reported as an expected
failure with the mark ‘x’
• The second test is never run and marked as ‘s’
• The third and four tests may or may not be run
depending on the current Python version and
operation system.
Ignoring broken tests
How much testing is enough?
• How can we tell how well our code is tested?
• This is a hard question, and we actually do not know whether our code is
tested properly and throughout.
• How do we know how much of our code is being tested and how
much is broken?
• This is an easy question, and we can use the code coverage tool to
check.
• We can check the number of lines that are in the program and get an
estimation of what percentage of the code was tested or
covered.
How much testing is enough?
• In Python, the most popular tool for testing code coverage is called
‘coverage.py’
• It can be installed using the ‘pip3 install coverage’ command
• coverage.py works in three phases:
• Execution: Coverage.py runs your code, and monitors it to see what lines were
executed. (command ‘coverage run <your_code>’)
• Analysis: Coverage.py examines your code to determine what lines could have run.
• Reporting: Coverage.py combines the results of execution and analysis to produce a
coverage number and an indication of missing execution. (command ‘coverage
report’ or ‘coverage html’)
How much testing is enough?
• Execution: ‘coverage run -m <your_code>’
How much testing is enough?
• Analysis & Reporting: command ‘coverage report’ and ‘coverage html’
How much testing is enough?
HTML reports
Python 3 Object-Oriented
Programming
• Preface
• Chapter 2: Objects in Python
• Chapter 12: Testing object-oriented
programs
Python
• https://www.python.org/
• https://docs.python.org/3/library/unittest.h
tml#
Suggested
reading

More Related Content

Similar to Object oriented programming design and implementation (20)

Python training
Python trainingPython training
Python training
Kunalchauhan76
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
RohitKumar639388
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
package module in the python environement.pptx
package module in the python environement.pptxpackage module in the python environement.pptx
package module in the python environement.pptx
MuhammadAbdullah311866
 
Introduction to python programming 2
Introduction to python programming   2Introduction to python programming   2
Introduction to python programming 2
Giovanni Della Lunga
 
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
 
Get Data Science with Python 1st Edition Coll. free all chapters
Get Data Science with Python 1st Edition Coll. free all chaptersGet Data Science with Python 1st Edition Coll. free all chapters
Get Data Science with Python 1st Edition Coll. free all chapters
bagzimanki03
 
the roadmap of python for developer beginner
the roadmap of python for developer  beginnerthe roadmap of python for developer  beginner
the roadmap of python for developer beginner
aqibfunclub7
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
Raghu Kumar
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptx
sushil155005
 
Standard Libraries in Python Programming
Standard Libraries in Python ProgrammingStandard Libraries in Python Programming
Standard Libraries in Python Programming
Rohan Chougule
 
Data Science with Python 1st Edition Coll. download pdf
Data Science with Python 1st Edition Coll. download pdfData Science with Python 1st Edition Coll. download pdf
Data Science with Python 1st Edition Coll. download pdf
ollerpudi
 
Data Science with Python 1st Edition Coll.
Data Science with Python 1st Edition Coll.Data Science with Python 1st Edition Coll.
Data Science with Python 1st Edition Coll.
leyitoqata
 
Using python libraries.pptx , easy ppt to study class 12
Using python libraries.pptx , easy ppt to study class 12Using python libraries.pptx , easy ppt to study class 12
Using python libraries.pptx , easy ppt to study class 12
anikedheikhamsingh
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
Sushant Mane
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
Audrey Roy
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
VijaySharma802
 
Python Software Engineering Python Software Engineering
Python Software Engineering Python Software EngineeringPython Software Engineering Python Software Engineering
Python Software Engineering Python Software Engineering
ssuser1c86e3
 
Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)
Kiran Jonnalagadda
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
RohitKumar639388
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
package module in the python environement.pptx
package module in the python environement.pptxpackage module in the python environement.pptx
package module in the python environement.pptx
MuhammadAbdullah311866
 
Introduction to python programming 2
Introduction to python programming   2Introduction to python programming   2
Introduction to python programming 2
Giovanni Della Lunga
 
Get Data Science with Python 1st Edition Coll. free all chapters
Get Data Science with Python 1st Edition Coll. free all chaptersGet Data Science with Python 1st Edition Coll. free all chapters
Get Data Science with Python 1st Edition Coll. free all chapters
bagzimanki03
 
the roadmap of python for developer beginner
the roadmap of python for developer  beginnerthe roadmap of python for developer  beginner
the roadmap of python for developer beginner
aqibfunclub7
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
Raghu Kumar
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptx
sushil155005
 
Standard Libraries in Python Programming
Standard Libraries in Python ProgrammingStandard Libraries in Python Programming
Standard Libraries in Python Programming
Rohan Chougule
 
Data Science with Python 1st Edition Coll. download pdf
Data Science with Python 1st Edition Coll. download pdfData Science with Python 1st Edition Coll. download pdf
Data Science with Python 1st Edition Coll. download pdf
ollerpudi
 
Data Science with Python 1st Edition Coll.
Data Science with Python 1st Edition Coll.Data Science with Python 1st Edition Coll.
Data Science with Python 1st Edition Coll.
leyitoqata
 
Using python libraries.pptx , easy ppt to study class 12
Using python libraries.pptx , easy ppt to study class 12Using python libraries.pptx , easy ppt to study class 12
Using python libraries.pptx , easy ppt to study class 12
anikedheikhamsingh
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
Sushant Mane
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
Audrey Roy
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
VijaySharma802
 
Python Software Engineering Python Software Engineering
Python Software Engineering Python Software EngineeringPython Software Engineering Python Software Engineering
Python Software Engineering Python Software Engineering
ssuser1c86e3
 
Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)
Kiran Jonnalagadda
 

More from afsheenfaiq2 (19)

object oriented porgramming using Java programming
object oriented porgramming using Java programmingobject oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Anime Display for Weekly Passion Hour Club
Anime Display for Weekly Passion Hour ClubAnime Display for Weekly Passion Hour Club
Anime Display for Weekly Passion Hour Club
afsheenfaiq2
 
Creating Python Variables using Replit software
Creating Python Variables using Replit softwareCreating Python Variables using Replit software
Creating Python Variables using Replit software
afsheenfaiq2
 
Introduction to Declaring Functions in Python
Introduction to Declaring Functions in PythonIntroduction to Declaring Functions in Python
Introduction to Declaring Functions in Python
afsheenfaiq2
 
Sample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionSample Exam Questions on Python for revision
Sample Exam Questions on Python for revision
afsheenfaiq2
 
GR 12 IOT Week 2.pptx
GR 12 IOT Week 2.pptxGR 12 IOT Week 2.pptx
GR 12 IOT Week 2.pptx
afsheenfaiq2
 
IOT Week 20.pptx
IOT Week 20.pptxIOT Week 20.pptx
IOT Week 20.pptx
afsheenfaiq2
 
Lesson 17 - Pen Shade and Stamp.pptx
Lesson 17 - Pen Shade and Stamp.pptxLesson 17 - Pen Shade and Stamp.pptx
Lesson 17 - Pen Shade and Stamp.pptx
afsheenfaiq2
 
AP CS PD 1.3 Week 4.pptx
AP CS PD 1.3 Week 4.pptxAP CS PD 1.3 Week 4.pptx
AP CS PD 1.3 Week 4.pptx
afsheenfaiq2
 
2D Polygons using Pen tools- Week 21.pptx
2D Polygons using Pen tools- Week 21.pptx2D Polygons using Pen tools- Week 21.pptx
2D Polygons using Pen tools- Week 21.pptx
afsheenfaiq2
 
Chapter 11 Strings.pptx
Chapter 11 Strings.pptxChapter 11 Strings.pptx
Chapter 11 Strings.pptx
afsheenfaiq2
 
Lesson 10_Size Block.pptx
Lesson 10_Size Block.pptxLesson 10_Size Block.pptx
Lesson 10_Size Block.pptx
afsheenfaiq2
 
CH05.ppt
CH05.pptCH05.ppt
CH05.ppt
afsheenfaiq2
 
Chapter05.ppt
Chapter05.pptChapter05.ppt
Chapter05.ppt
afsheenfaiq2
 
Gr 12 - Buzzer Project on Sound Production (W10).pptx
Gr 12 - Buzzer Project on Sound Production (W10).pptxGr 12 - Buzzer Project on Sound Production (W10).pptx
Gr 12 - Buzzer Project on Sound Production (W10).pptx
afsheenfaiq2
 
Network Topologies
Network TopologiesNetwork Topologies
Network Topologies
afsheenfaiq2
 
IoT-Week1-Day1-Lecture.pptx
IoT-Week1-Day1-Lecture.pptxIoT-Week1-Day1-Lecture.pptx
IoT-Week1-Day1-Lecture.pptx
afsheenfaiq2
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
afsheenfaiq2
 
object oriented porgramming using Java programming
object oriented porgramming using Java programmingobject oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Anime Display for Weekly Passion Hour Club
Anime Display for Weekly Passion Hour ClubAnime Display for Weekly Passion Hour Club
Anime Display for Weekly Passion Hour Club
afsheenfaiq2
 
Creating Python Variables using Replit software
Creating Python Variables using Replit softwareCreating Python Variables using Replit software
Creating Python Variables using Replit software
afsheenfaiq2
 
Introduction to Declaring Functions in Python
Introduction to Declaring Functions in PythonIntroduction to Declaring Functions in Python
Introduction to Declaring Functions in Python
afsheenfaiq2
 
Sample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionSample Exam Questions on Python for revision
Sample Exam Questions on Python for revision
afsheenfaiq2
 
GR 12 IOT Week 2.pptx
GR 12 IOT Week 2.pptxGR 12 IOT Week 2.pptx
GR 12 IOT Week 2.pptx
afsheenfaiq2
 
Lesson 17 - Pen Shade and Stamp.pptx
Lesson 17 - Pen Shade and Stamp.pptxLesson 17 - Pen Shade and Stamp.pptx
Lesson 17 - Pen Shade and Stamp.pptx
afsheenfaiq2
 
AP CS PD 1.3 Week 4.pptx
AP CS PD 1.3 Week 4.pptxAP CS PD 1.3 Week 4.pptx
AP CS PD 1.3 Week 4.pptx
afsheenfaiq2
 
2D Polygons using Pen tools- Week 21.pptx
2D Polygons using Pen tools- Week 21.pptx2D Polygons using Pen tools- Week 21.pptx
2D Polygons using Pen tools- Week 21.pptx
afsheenfaiq2
 
Chapter 11 Strings.pptx
Chapter 11 Strings.pptxChapter 11 Strings.pptx
Chapter 11 Strings.pptx
afsheenfaiq2
 
Lesson 10_Size Block.pptx
Lesson 10_Size Block.pptxLesson 10_Size Block.pptx
Lesson 10_Size Block.pptx
afsheenfaiq2
 
Gr 12 - Buzzer Project on Sound Production (W10).pptx
Gr 12 - Buzzer Project on Sound Production (W10).pptxGr 12 - Buzzer Project on Sound Production (W10).pptx
Gr 12 - Buzzer Project on Sound Production (W10).pptx
afsheenfaiq2
 
Network Topologies
Network TopologiesNetwork Topologies
Network Topologies
afsheenfaiq2
 
IoT-Week1-Day1-Lecture.pptx
IoT-Week1-Day1-Lecture.pptxIoT-Week1-Day1-Lecture.pptx
IoT-Week1-Day1-Lecture.pptx
afsheenfaiq2
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Ad

Recently uploaded (20)

Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Ad

Object oriented programming design and implementation

  • 1. CSIT121 Object-Oriented Design and Programming Dr. Fenghui Ren School of Computing and Information Technology University of Wollongong 1
  • 2. Lecture 4 outline • Modules and packages • Third-party libraries • Test-driven development • Unittest module • Code coverage 2
  • 3. Modules • For small programs, we can put all our classes into one file and add a little script at the end to start them interacting. • For large programs, it can become difficult to find the one class that needs to be edited among the many classes we’ve defined. • We need to use modules. • Modules are simply Python files. One Python file equals one module. • If we have multiple modules with different class definitions, we can load classes from one module to reuse them in the other modules. E.g. put all classes and functions related to the database access into the module ‘database.py’.
  • 4. Modules • The ‘import’ statement is used for importing modules or specific classes or functions from modules. E.g. we used the import statement to get Python’s built-in math module and use its sqrt function in the distance calculation Suppose we have: • A module called ‘database.py’ which contains a Database class • A second module called ‘products.py’ which responsible for product- related queries. • ‘products.py’ needs to instantiate the Database class from ‘database.py’ module so that it can execute queries on the product table in the database. • We need import Database class in the products module.
  • 5. Modules • To import the whole database module into the products namespace so any class or function in the database module can be accessed using the ‘database.<something>’ notation. Import database db = database.Database() # Do queries on db
  • 6. Modules • To import just one class (Database class) from the database module into the products namespace so all the class functions can be accessed directly. from database import Database db = Database() # Do queries on db
  • 7. Modules • If the products module already has a class called Database, and we don’t want the two names to be confused, we can rename the imported class when used inside the products module from database import Database as DB db_product = Database() Db_database = DB() # Do queries on db
  • 8. Modules • We can also import multiple classes in one statement. If our database module also contains a Query class, we can import both classes as follows. from database import Database, Query db = Database() query = Query() # Do queries on db via query
  • 9. Modules • Don’t do this from database import * Because, • You will never know when classes will be used • Not easy to check the class details (using help()) and maintain your program • Unexpected classes and functions will be imported. For example, it will also import any classes or modules that were themselves imported into that file.
  • 10. Modules • For fun, try typing ‘import this’ in your interactive interpreter. You will get a poem about Python philosophy. 
  • 11. Package • As a project grows into a collection of more and more modules, it is better to add another level of abstract. • As modules equal files, one straightforward solution is to organise files with folders (called packages). • A package is a collection of modules in a folder. The name of the package is the name of the folder. • We need to tell Python that a folder is a package to distinguish it from other folders in the directory. • We need to place a special file in the package folder named ‘ init .py’. • If we forget this file, we won’t be able to import modules from that folder.
  • 12. Package • Put our modules inside an ecommerce directory in our working folder (parent_directory) • The working folder also contains a main.py module to start the program. • We can add another payment directory inside the ecommerce directory for various payment options. • The folder hierarchy will look like this.
  • 13. Package In Python 3, there are two ways of importing modules from a package: absolute imports and relative imports. • Absolut imports specify the complete path to the module in the package, functions, or classes we want to import • Relative imports find a class, function, or module as it is positioned relative to the current module in the package.
  • 14. Package Absolute imports • If we need access to the Product class inside the products module, we could use any of these syntaxes to perform an absolute import.
  • 15. Package Absolute imports Which way is better? It depends. • The first way is normally used if you have some kind of name conflict from multiple modules. You have to specify the whole path before the function calls. • If you only need to import one or two classes, you can use the second way. Easy to call functions. • If there are dozens of classes and functions inside the module that you want to use, you can import the module using the third way.
  • 16. Package Relative imports • If we are working in the products module and we want to import the Database class from the database module next to it, we could use a relative import. from .database import Database • The period ‘.’ in front of the database says ‘using the database module inside the current package’. • The current package refers to the package containing the module (products.py) we are currently working in, i.e., the ecommerce package.
  • 17. Package Relative imports • If we were editing the square.py module inside the payments package, we want to use the database package inside the parent package. from ..database import Database • We use more periods to go further up the hierarchy. • If we had an ecommerce.contact package containing an email module and wanted to import the send_mail function. from ..contact.email import send_mail
  • 18. Inside a module • We specify variables, classes or functions inside modules. • They can be a handy way to shore the global state without namespace conflicts. • For example, it might make more sense to have only one database object globally available from the database module. • The database module might look like this:
  • 19. Inside a module • Then we can use any of the import methods we’ve discussed to access the database object, such as • In some situations, it may be better to create objects until it is actually needed to avoid unnecessary delay in the program.
  • 20. Inside a module • All module-level code is executed immediately at the time it is imported. • However, the internal code of functions will not be executed until the function is called. • To simplify the process, we should always put our start-up code in a function (conventionally called ‘main’) and only execute that function when we know we are running the module as a script, but not when our code is being imported from a different script. • We can do this by guarding the call to ‘main’ inside a conditional statement.
  • 21. Inside a module Important note: Make it a policy to wrap all your scripts in an ‘if name == “ main ”:’ your_testing_code’ pattern in case you write a function that you may want to be imported by other code at some point in the future.
  • 22. Third-party libraries • You can find third-party libraries on the Python Package Index (PyPI) at http://pypi.python.org/. Then you can install the libraries with a tool called ‘pip’ • However, ‘pip’ is not pre-installed in Python, please follow the instructions to download and install ‘pip’: http://pip.readthedocs.org/ • For Python 3.4 and higher, you can use a built-in tool called ‘ensurepip’ by installing it with the command ‘$python3 –m ensurepip’ • Then, you can install libraries via the command ‘$pip install <library_name>’ • Then the third-party library will be installed directly into your system Python directory.
  • 23. Third-party libraries We will learn Matplotlib (a low-level graph plotting library) in this subject.
  • 24. Program Testing Why test? • To ensure that the code is working the way the developer thinks it should • To ensure that the code continues working when we make changes • To ensure that the developer understood the requirements • To ensure that the code we are writing has a maintainable interface
  • 25. Test-driven development methdology Principle • Write tests for a segment of code first • Test your code (it will fail because you don’t write the code yet) • Write your code and ensure the test passes • Write another test for the next segment of your code • Write your code and ensure the test passes … It is fun. You build a puzzle for yourself first, then you solve it!
  • 26. Test-driven development methodology The test-driven development methodology • ensures that tests really get written; • forces us to consider exactly how the code will be used. • It tells us what methods objects need to have and how attributes will be accessed; • helps us break up the initial problem into smaller, testable problems, and then to recombine the tested solutions into larger, also tested, solutions; • helps us to discover anomalies in the design that force us to consider new aspects of the software; • will not leave the testing job to the program users.
  • 27. Unit Test • Same as Java, Python also has a built-in test library called ‘unittest’ • ‘unittest’ provides several tools for creating and running unit tests. • The most important one is the ‘TestCase’ class. • ‘TestCase’ class provides a set of methods that allow us to compare values, set up tests, and clean up when the tests have finished.
  • 28. Unit Test • Create a subclass of TestCase (we will introduce the inheritance next lecture) and write individual methods to do the actual testing. • These method names must all start with the prefix ‘test’. • TestCase class will automatically run all the test methods and report the test results
  • 29. Unit Test • Pass the test
  • 30. Unit Test • fail the test
  • 33. Reducing boilerplate and cleaning up • No need to write the same setup code for each test method if the test cases are the same. • We can use the ‘setUp()’ method on the TestCase class to perform initialisation for test methods.
  • 34. Organise your test classes • We should divide our test classes into modules and packages (keep them organized) • Python’s discover module (‘python3 –m unittest’) can find any TestCase objects in modules if your tests module starts with the keyword ‘test’. • Most Python programmers also choose to put their tests in a separate package (usually named ‘tests/’ alongside their source directory).
  • 36. Ignoring broken tests • Sometimes, a test is known to fail, but we don’t want to report the failure. • Python provides a few decorators to mark tests that are expected to fail or to be skipped under known conditions. • ‘@expectedFailure’, ‘@skip(reason)’, ‘@skipIf(condition, reason)’, ‘@skipUnless(condition, reason)’
  • 37. Ignoring broken tests Tests results: • The first test fails and is reported as an expected failure with the mark ‘x’ • The second test is never run and marked as ‘s’ • The third and four tests may or may not be run depending on the current Python version and operation system.
  • 39. How much testing is enough? • How can we tell how well our code is tested? • This is a hard question, and we actually do not know whether our code is tested properly and throughout. • How do we know how much of our code is being tested and how much is broken? • This is an easy question, and we can use the code coverage tool to check. • We can check the number of lines that are in the program and get an estimation of what percentage of the code was tested or covered.
  • 40. How much testing is enough? • In Python, the most popular tool for testing code coverage is called ‘coverage.py’ • It can be installed using the ‘pip3 install coverage’ command • coverage.py works in three phases: • Execution: Coverage.py runs your code, and monitors it to see what lines were executed. (command ‘coverage run <your_code>’) • Analysis: Coverage.py examines your code to determine what lines could have run. • Reporting: Coverage.py combines the results of execution and analysis to produce a coverage number and an indication of missing execution. (command ‘coverage report’ or ‘coverage html’)
  • 41. How much testing is enough? • Execution: ‘coverage run -m <your_code>’
  • 42. How much testing is enough? • Analysis & Reporting: command ‘coverage report’ and ‘coverage html’
  • 43. How much testing is enough? HTML reports
  • 44. Python 3 Object-Oriented Programming • Preface • Chapter 2: Objects in Python • Chapter 12: Testing object-oriented programs Python • https://www.python.org/ • https://docs.python.org/3/library/unittest.h tml# Suggested reading