CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf ·...

55
CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators Sven Schmit stanford.edu/~schmit/cme193 6: Classes and iterators 6-1

Transcript of CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf ·...

Page 1: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

CME 193: Introduction to Scientific Python

Lecture 6: Classes and iterators

Sven Schmit

stanford.edu/~schmit/cme193

6: Classes and iterators 6-1

Page 2: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Contents

Classes

Generators and Iterators

Exercises

6: Classes and iterators 6-2

Page 3: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Defining our own objects

So far, we have seen many objects in the course that come standard

with Python.

Integers

Strings

Lists

Dictionaries

etc

But often one wants to build more complicated structures.

6: Classes and iterators 6-3

Page 4: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Defining our own objects

So far, we have seen many objects in the course that come standard

with Python.

Integers

Strings

Lists

Dictionaries

etc

But often one wants to build more complicated structures.

6: Classes and iterators 6-4

Page 5: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

From brick and mortar to houses

So far, I have taught you about brick and mortar, now it’s time to learn

how to build a house.

6: Classes and iterators 6-5

Page 6: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Consider ‘building’ a house in Python

Suppose you have a program that needs to store all information about

houses. How are we storing all information about this house?

A house might be a list with two elements, one for rooms, one for

construction information

house = [{bathroom: ..., kitchen: ...}, [brick, wood, ...]]

For the rooms we might again want to know about what’s in the

room, what it’s made off

So bathroom = [materials, bathtub, sink], where materials is a list

We get a terribly nested structure, impossible to handle!

6: Classes and iterators 6-6

Page 7: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Consider ‘building’ a house in Python

Suppose you have a program that needs to store all information about

houses. How are we storing all information about this house?

A house might be a list with two elements, one for rooms, one for

construction information

house = [{bathroom: ..., kitchen: ...}, [brick, wood, ...]]

For the rooms we might again want to know about what’s in the

room, what it’s made off

So bathroom = [materials, bathtub, sink], where materials is a list

We get a terribly nested structure, impossible to handle!

6: Classes and iterators 6-7

Page 8: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Consider ‘building’ a house in Python

Suppose you have a program that needs to store all information about

houses. How are we storing all information about this house?

A house might be a list with two elements, one for rooms, one for

construction information

house = [{bathroom: ..., kitchen: ...}, [brick, wood, ...]]

For the rooms we might again want to know about what’s in the

room, what it’s made off

So bathroom = [materials, bathtub, sink], where materials is a list

We get a terribly nested structure, impossible to handle!

6: Classes and iterators 6-8

Page 9: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Consider ‘building’ a house in Python

Suppose you have a program that needs to store all information about

houses. How are we storing all information about this house?

A house might be a list with two elements, one for rooms, one for

construction information

house = [{bathroom: ..., kitchen: ...}, [brick, wood, ...]]

For the rooms we might again want to know about what’s in the

room, what it’s made off

So bathroom = [materials, bathtub, sink], where materials is a list

We get a terribly nested structure, impossible to handle!

6: Classes and iterators 6-9

Page 10: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Object Oriented Programming

Construct our own objects

House

Room

etc

Structure in familiar form

Much easier to understand

6: Classes and iterators 6-10

Page 11: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Object Oriented Programming

Construct our own objects

House

Room

etc

Structure in familiar form

Much easier to understand

6: Classes and iterators 6-11

Page 12: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Object Oriented Programming

Express computation in terms of objects, which are instances of classes

Class Blueprint (only one)

Object Instance (many)

Classes specify attributes (data) and methods to interact with the

attributes.

6: Classes and iterators 6-12

Page 13: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Object Oriented Programming

Express computation in terms of objects, which are instances of classes

Class Blueprint (only one)

Object Instance (many)

Classes specify attributes (data) and methods to interact with the

attributes.

6: Classes and iterators 6-13

Page 14: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Python’s way

In languages such as C++ and Java, classes provide data protection

with private and public attributes and methods.

Not the case in Python: only basics such as inheritance.

Up to programmers not to abuse power: works well in practice and leads

to simple code.

6: Classes and iterators 6-14

Page 15: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Simplest example

# define class:class Leaf:

pass

# instantiate objectleaf = Leaf()

print leaf# <__main__.Leaf instance at 0x10049df80>

6: Classes and iterators 6-15

Page 16: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Initializing an object

We can define how a class is instantiated by defining the __init__

method.

For the more seasoned programmer: in Python there can only be one

constructor method.

6: Classes and iterators 6-16

Page 17: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Initializing an object

The init or constructor method.

class Leaf:n_leafs = 0 # class variable: shared

def __init__(self, color):self.color = color # private variableLeaf.n_leafs += 1

redleaf = Leaf(’red’)blueleaf = Leaf(’blue’)

print redleaf.color# redprint Leaf.n_leafs# 2

Note how we access object attributes.

6: Classes and iterators 6-17

Page 18: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Self

The self parameter seems strange at first sight.

It refers to the the object (instance) itself.

Hence self.color = color sets the color of the object self.color

equal to the variable color.

6: Classes and iterators 6-18

Page 19: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Another example

Classes have methods (similar to functions)

class Stock():def __init__(self, name, symbol, prices=[]):

self.name = nameself.symbol = symbolself.prices = prices

def high_price(self):if len(self.prices) == 0:

return ’MISSING PRICES’return max(self.prices)

apple = Stock(’Apple’, ’APPL’, [500.43, 570.60])print apple.high_price()

Recall: list.append() or dict.items(). These are simply class methods!

6: Classes and iterators 6-19

Page 20: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Another example

Classes have methods (similar to functions)

class Stock():def __init__(self, name, symbol, prices=[]):

self.name = nameself.symbol = symbolself.prices = prices

def high_price(self):if len(self.prices) == 0:

return ’MISSING PRICES’return max(self.prices)

apple = Stock(’Apple’, ’APPL’, [500.43, 570.60])print apple.high_price()

Recall: list.append() or dict.items(). These are simply class methods!

6: Classes and iterators 6-20

Page 21: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Inheritance

Suppose we first define an abstract class

class Animal:def __init__(self, n_legs, color):

self.n_legs = n_legsself.color = color

def make_noise(self):print ’noise’

6: Classes and iterators 6-21

Page 22: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Inheritance

We can define sub classes and inherit from another class.

class Dog(Animal):def __init__(self, color, name):

Animal.__init__(self, 4, color)self.name = name

def make_noise(self):print self.name + ’: ’ + ’woof’

bird = Animal(2, ’white’)bird.make_noise()# noisebrutus = Dog(’black’, ’Brutus’)brutus.make_noise()# Brutus: woofshelly = Dog(’white’, ’Shelly’)shelly.make_noise()# Shelly: woof

6: Classes and iterators 6-22

Page 23: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Why inheritance

Often very useful:

An abstract class that implements general functionality can be combined

with several subclasses that implement details.

Example: statistical package with a general Model class. Subclasses can

include Linear regression, Logistic regression, etc.

6: Classes and iterators 6-23

Page 24: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Why inheritance

Often very useful:

An abstract class that implements general functionality can be combined

with several subclasses that implement details.

Example: statistical package with a general Model class. Subclasses can

include Linear regression, Logistic regression, etc.

6: Classes and iterators 6-24

Page 25: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Base methods

Base methods which you can override

__init__: Constructor

__del__: Destructor

__repr__: Represent the object (machine)

__str__: Represent the object (human)

__cmp__: Compare

6: Classes and iterators 6-25

Page 26: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Compare

The __cmp__ method should be implemented as follows:

If self is smaller than other, return a negative value

If self and other are equal, return 0

If self is larger than other, return a positive value

6: Classes and iterators 6-26

Page 27: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

More useful methods

Some more on this later!

__contains__ for the in keyword

__iter__ and next for iterators

6: Classes and iterators 6-27

Page 28: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Exercise

One of the exercises today is to implement a class for rational numbers,

i.e. fractions.

Let’s start together

6: Classes and iterators 6-28

Page 29: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Setup

What information should the class hold?

Numerator

Denominator

6: Classes and iterators 6-29

Page 30: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Setup

What information should the class hold?

Numerator

Denominator

6: Classes and iterators 6-30

Page 31: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Init

Implement the __init__ method

class Rational:def __init__(self, p, q):

self.p = pself.q = q

6: Classes and iterators 6-31

Page 32: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Init

Implement the __init__ method

class Rational:def __init__(self, p, q):

self.p = pself.q = q

6: Classes and iterators 6-32

Page 33: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Issues

What are the issues with the code?

class Rational:def __init__(self, p, q):

self.p = pself.q = q

Ignore the division by 0 for now, more on that next lecture.

6: Classes and iterators 6-33

Page 34: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Issues

What are the issues with the code?

class Rational:def __init__(self, p, q):

self.p = pself.q = q

Ignore the division by 0 for now, more on that next lecture.

6: Classes and iterators 6-34

Page 35: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Greatest common divisor

We really would like to ensure that 1020 and 1

2 are the same number.

Implement a gcd(a, b) function that computes the greatest common

divisor of a and b.

Hint: Google Euclidean algorithm

6: Classes and iterators 6-35

Page 36: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Greatest common divisor

def gcd(a, b):if b == 0:

return aelse:

return gcd(b, a%b)

class Rational:def __init__(self, p, q):

g = gcd(p, q)self.p = p / gself.q = q / g

6: Classes and iterators 6-36

Page 37: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Greatest common divisor

def gcd(a, b):if b == 0:

return aelse:

return gcd(b, a%b)

class Rational:def __init__(self, p, q):

g = gcd(p, q)self.p = p / gself.q = q / g

6: Classes and iterators 6-37

Page 38: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Add two rational numbers

Implement that __add__ method to add two rational numbers as in

Rational(10,2) + Rational(4,3)

class Rational:# ...def __add__(self, other):

p = self.p * other.q + other.p * self.qq = self.q * other.qreturn Rational(p, q)

# ...

6: Classes and iterators 6-38

Page 39: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Add two rational numbers

Implement that __add__ method to add two rational numbers as in

Rational(10,2) + Rational(4,3)

class Rational:# ...def __add__(self, other):

p = self.p * other.q + other.p * self.qq = self.q * other.qreturn Rational(p, q)

# ...

6: Classes and iterators 6-39

Page 40: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Contents

Classes

Generators and Iterators

Exercises

6: Classes and iterators 6-40

Page 41: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

For loops

Recall that in Python we can loop over the elements in a list simply by

saying

for elem in li:

# do something

We also say that we are iterating over the list.

6: Classes and iterators 6-41

Page 42: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Fibonnaci numbers

Say we want to iterate over the first n Fibonacci numbers:

for elem in fib(n):

# do something

How to implement Fib(n)?

6: Classes and iterators 6-42

Page 43: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

fib(n)

We can use our function from the lists homework, which returns a list

with the first n Fibonacci numbers.

What happens when n is large, say n = 106 or more generally n = 10k?

Problem: we have to store the entire list...

Eventually we will run out of memory.

6: Classes and iterators 6-43

Page 44: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

fib(n)

We can use our function from the lists homework, which returns a list

with the first n Fibonacci numbers.

What happens when n is large, say n = 106 or more generally n = 10k?

Problem: we have to store the entire list...

Eventually we will run out of memory.

6: Classes and iterators 6-44

Page 45: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

fib(n)

We can use our function from the lists homework, which returns a list

with the first n Fibonacci numbers.

What happens when n is large, say n = 106 or more generally n = 10k?

Problem: we have to store the entire list...

Eventually we will run out of memory.

6: Classes and iterators 6-45

Page 46: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Generators

Instead, we can use so called generators

Only difference with functions: use yield instead of return

6: Classes and iterators 6-46

Page 47: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Example: Range

def myrange(end, start=0, step=1):if start > end:

start, end = end, startcurrent = startyield currentwhile current+step < end:

current += stepyield current

6: Classes and iterators 6-47

Page 48: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Advantage over lists

Note, in this case we never store the entire list.

This scales much better!

(though Fibonacci numbers scale poorly, but you get the idea)

6: Classes and iterators 6-48

Page 49: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Back to Fibonacci

How to write a generator for the Fibonacci sequence?

def fib(n):a, b = 0, 1i = 1while i < n:

a, b = b, a + bi += 1yield a

for elem in fib(10):print elem

6: Classes and iterators 6-49

Page 50: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Generators are a simple form of iterators

Iterators underlie many aspects of Python such as

List comprehensions

Generators

6: Classes and iterators 6-50

Page 51: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Iterators are classes

Init method to initialize iterator

__iter__ method to set up the iterator

next method to loop over the entries

More control, but also more code.

6: Classes and iterators 6-51

Page 52: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Range as iterator

A slight overkill...

class Range:def __init__(self, end, start=0, step=1):

if end < start:end, start = start, end

self.current = startself.end = endself.step = step

def __iter__(self):return self

def next(self):c = self.currentif c >= self.end:

raise StopIterationself.current += self.stepreturn c

6: Classes and iterators 6-52

Page 53: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Fibonacci iterator

class Fib:def __init__(self, n):

self.n = nself.i = 0

def __iter__(self):self.a = 0self.b = 1return self

def next(self):if self.i >= self.n: raise StopIterationself.i += 1self.a, self.b = self.b, self.a + self.breturn self.a

6: Classes and iterators 6-53

Page 54: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Contents

Classes

Generators and Iterators

Exercises

6: Classes and iterators 6-54

Page 55: CME193: IntroductiontoScientificPython Lecture6 ...stanford.edu/~schmit/cme193/lec/lec6.pdf · CME193: IntroductiontoScientificPython Lecture6: Classesanditerators SvenSchmit stanford.edu/~schmit/cme193

Exercises

Next lecture: Eli Bressert

6: Classes and iterators 6-55