Lecture_8#_comprehension_exceptions_2
Lecture_8#_comprehension_exceptions_2
Using
Python
Teemu Matilainen
teemu.matilainen@savo
nia.fi
Lecture 8#
Create a MyShoppingList
class and adjust the class
so that it is iterable and
can thus be used as
follows:
iter()
• 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
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.
The program should include methods for calculating the area of rectangles and
circles. Handle exceptions appropriately for negative dimensions and invalid shape
types.