0% found this document useful (0 votes)
2 views

Lecture_8#_comprehension_exceptions_2

The document discusses Object Oriented Programming in Python, focusing on comprehensions, exception handling, and creating custom exceptions. It provides examples of how to implement iterators, handle exceptions, and design a custom exception class for a shopping list and an area calculator program. The document emphasizes the importance of exception handling in programming to manage errors gracefully.

Uploaded by

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

Lecture_8#_comprehension_exceptions_2

The document discusses Object Oriented Programming in Python, focusing on comprehensions, exception handling, and creating custom exceptions. It provides examples of how to implement iterators, handle exceptions, and design a custom exception class for a shopping list and an area calculator program. The document emphasizes the importance of exception handling in programming to manage errors gracefully.

Uploaded by

Dong Nguyen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Object Oriented Programming

Using
Python

Teemu Matilainen
teemu.matilainen@savo
nia.fi
Lecture 8#

• You know how to use comprehensions within own classes


• You realize what exceptions are
• You realize how exceptions are used
• You are able to catch an exception
• You are able to throw an exception
• You are able to design an exception class of your own
Exercise…

Create a MyShoppingList
class and adjust the class
so that it is iterable and
can thus be used as
follows:
iter()

• The iter() function is used to obtain an iterator from an object that


implements the iteration protocol.

• If the object has a __iter__() method, the iter() function calls this method to
get the iterator.
• If the object doesn't have a __iter__() method but has a __getitem__()
method, iter() creates an iterator that accesses elements using integer
indices.
• If neither method is present, iter() raises a TypeError.

next()
• The next() function is used to retrieve the next item from an iterator.
• It takes an iterator as its first argument and an optional default value as its
second argument.
• If the iterator has more items, next() returns the next item; otherwise, it
raises a StopIteration exception if no default value is provided.
• If a default value is provided, next() returns the default value when the
iterator is exhausted.
Simple Iteration
Another more 'pythonic' approach to creating lists
from existing ones is through the use of list
comprehensions. The concept involves condensing
onto a single line both the operation applied to
each item in the list and the assignment of the
results to a new list.
Comprehensions
With
Own classes

Comprehensions can prove valuable in handling or


creating instances of custom classes, as demonstrated
in the upcoming examples.
Comprehensions
With
Own classes
Comprehensions
With
Own classes
Comprehension
and class
methods…

In reality, the expression used within the list


comprehension statement can be any valid Python
expression. You can even invoke a class method that
you have defined yourself:
Comprehension for Shopping list
Exception handling

Exception handling is a crucial aspect of Python programming. It allows


you to gracefully handle errors and unexpected situations that may occur
during the execution of your code. Python provides a mechanism to catch
and deal with exceptions using the try, except, finally, and else blocks.
Exception handling
Its July 20, 1969, Apollo 11 mission was
close to touchdown on the moon. Neil
Amstrong, Buzz Aldrin, and Michel
Collins checking last-minute preparation
for landing. Over their, onboard computer
something started flashing it was Error
1201 followed by error 1202. Human
beings first landing on the moon is
jeopardized by two computer errors…
Here's a basic example
of exception handling in
Python:
Exceptions?
What are exceptions?

• Exceptions are mechanism to handle runtime errors


• For example, user gives string ’one’ when asked an
integer

⇒ Conversion throws an exception


⇒ If the exception is not handled correct, the software
crashes

Basics of Programming: Janne Koponen


Catching Exceptions
continues

You can also catch multiple exceptions


and handle them

Basics of Programming: Janne Koponen


Catching
Exceptions.
Ain’t life
wonderful?
You can also catch multiple exceptions and handle
them differently…
Catching
Exceptions.
Finally we are
getting
somewhere…
Or are we? You can use the finally block to execute cleanup code
regardless of whether an exception occurs!
Catching
Exceptions. Is
there anything
else?
Else block can be used to execute code if no
exceptions are raised:
Catching
Exceptions.
Else &
Finally
Else + Finally
Catching
Exceptions.
All together!!
Raising
Custom
errors
To create your own custom
exceptions in Python, you can
subclass the built-in
Exception class or any other
built-in exception class. This
allows you to define specific
types of errors that are
relevant to your application.
Raising
Custom errors
continues…
You can create more
specific custom
exceptions by
subclassing other built-
in exceptions if your
custom exception
represents a specific The with statement ensures that the context management methods
type of error. For __enter__() and __exit__() of the object are properly called, regardless of
example, if your custom whether the block of code inside the with statement raises an exception or
not. This is commonly used for acquiring and releasing resources in a clean
exception is related to and predictable manner.
file operations, you
might subclass IOError. When working with files, using the with statement ensures that the file is
properly closed after its use, even if an exception occurs!
Raising
Custom errors • You can define your custom error class
constructor attributes…

continues…
• In Python, when you subclass a built-
in class like Exception to create a
custom exception class, it's generally
a good practice to call the __init__
Raising method of the superclass (the class
you're inheriting from) within your
Custom custom exception class's __init__
errors… method. This ensures that any
initialization logic defined in the
superclass is executed, which can be
important for proper exception
handling.
Assignment:

Create a program (class AreaCalculator) that calculates the area of geometric shapes.

The program should have “exception” classes: ShapeError as the base exception
class, and two subclasses, NegativeDimensionError and InvalidShapeError.

• ShapeError: Base exception class representing errors related to shape


calculations.
• NegativeDimensionError: Subclass of ShapeError, raised when the dimensions
(length, width, etc.) provided to calculate the area are negative.
• InvalidShapeError: Subclass of ShapeError, raised when an invalid shape type
is provided for calculation.

The program should include methods for calculating the area of rectangles and
circles. Handle exceptions appropriately for negative dimensions and invalid shape
types.

AreaCalculator has class methods:


• rectangle_area(self, length, width)
• circle_area(self, radius)
• calculate_area(self, shape_type, *args):

You might also like