Calling the multiplication method, however, works as desired:
In [ 37 ]: c.multiplication()
Out[37]: 300
To conclude the introduction into the main concepts of Python classes and objects, we
want to pick one other special method of importance: the iter method. It is called
whenever an iteration over an instance of a class is asked for. To begin with, define a list
of first names as follows:
In [ 38 ]: name_list = [‘Sandra’, ‘Lilli’, ‘Guido’, ‘Zorro’, ‘Henry’]
In Python it is usual to iterate over such lists directly — i.e., without the use of integer
counters or indexes:
In [ 39 ]: for name in name_list:
print name
Out[39]: Sandra
Lilli
Guido
Zorro
Henry
We are now going to define a new Python class that also returns values from a list, but the
list is sorted before the iterator starts returning values from the list. The class sorted_list
contains the following definitions:
init
To initialize the attribute elements we expect a list object, which we sort at
instantiation.
iter
This special method is called whenever an iteration is desired; it needs a definition of
a next method.
next
This method defines what happens per iteration step; it starts at index value
self.position = -1 and increases the value by 1 per call; it then returns the value
of elements at the current index value of self.position.
The class definition looks like this:
In [ 40 ]: class sorted_list(object):
def __init__(self, elements):
self.elements = sorted(elements) # sorted list object
def __iter__(self):
self.position = - 1
return self
def next(self):
if self.position == len(self.elements) - 1 :
raise StopIteration
self.position += 1
return self.elements[self.position]
Instantiate the class now with the name_list object:
In [ 41 ]: sorted_name_list = sorted_list(name_list)
The outcome is as desired — iterating over the new object returns the elements in
alphabetical order:
In [ 42 ]: for name in sorted_name_list:
print name