Lecture_7#_Inheritance_continues
Lecture_7#_Inheritance_continues
Using
Python
Teemu Matilainen
teemu.matilainen@savo
nia.fi
Lecture 7#
• Inheritance continues…
• You understand how to use iterators
• You know how to use comprehensions within own classes
• You are able to restrict the visibility of inherited attributes in a subclass
• You are able to restrict the visibility of inherited methods in a subclass
Inheritance … Thesis
class… Override…
Below we have a table for the visibility of attributes with different access modifiers:
Private self.__name no no
We use for statement to iterate through different data
structures, objects and collections of items. A typical
use:
Iteration?
Creating custom iterable classes is achievable as well.
This becomes beneficial when the primary function of
the class revolves around managing a group of items.
For instance, the Bookshelf class demonstrated earlier
would be well-suited for this, allowing a for loop to
conveniently navigate through the books on the shelf. A
One more similar scenario applies to a student register, where the
ability to iterate through the collection of students
operator would be advantageous.
example and
Iteration
Create a MyShoppingList
class and adjust the class
so that it is iterable and
can thus be used as
follows:
Exercise…
Create a MyShoppingList
class and adjust the class
so that it is iterable and
can thus be used as
follows:
Exercise…
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