16-object-oriented programming iics61a/su16/assets/... · inheritance • powerful idea in...

166
Lecture 16: Object-Oriented Programming II Marvin Zhang 07/19/2016

Upload: others

Post on 14-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Lecture 16: Object-Oriented Programming II

Marvin Zhang 07/19/2016

Page 2: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Announcements

Page 3: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Page 4: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:

Page 5: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:• Many students reevaluated their starting ability

Page 6: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:• Many students reevaluated their starting ability• Lab checkoffs: most think they’re worthwhile

Page 7: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:• Many students reevaluated their starting ability• Lab checkoffs: most think they’re worthwhile

• Others think it’s stressful or it’s too easy

Page 8: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:• Many students reevaluated their starting ability• Lab checkoffs: most think they’re worthwhile

• Others think it’s stressful or it’s too easy• They should be easy and not stressful

Page 9: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:• Many students reevaluated their starting ability• Lab checkoffs: most think they’re worthwhile

• Others think it’s stressful or it’s too easy• They should be easy and not stressful• It’s not unreasonable to ask you to come to lab

once a week

Page 10: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:• Many students reevaluated their starting ability• Lab checkoffs: most think they’re worthwhile

• Others think it’s stressful or it’s too easy• They should be easy and not stressful• It’s not unreasonable to ask you to come to lab

once a week• Homework 3 and Quiz 4 were so hard!

Page 11: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:• Many students reevaluated their starting ability• Lab checkoffs: most think they’re worthwhile

• Others think it’s stressful or it’s too easy• They should be easy and not stressful• It’s not unreasonable to ask you to come to lab

once a week• Homework 3 and Quiz 4 were so hard!

• Homework assignments are graded on effort

Page 12: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Survey Responses (Thanks!)

Highlights from the survey:• Many students reevaluated their starting ability• Lab checkoffs: most think they’re worthwhile

• Others think it’s stressful or it’s too easy• They should be easy and not stressful• It’s not unreasonable to ask you to come to lab

once a week• Homework 3 and Quiz 4 were so hard!

• Homework assignments are graded on effort• We will do coding quizzes a little differently

Page 13: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

Page 14: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!

Page 15: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!• Nope, it’s for your own good

Page 16: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!• Nope, it’s for your own good

• Have two midterms instead of quizzes!

Page 17: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!• Nope, it’s for your own good

• Have two midterms instead of quizzes!• Nope, it’s for your own good

Page 18: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!• Nope, it’s for your own good

• Have two midterms instead of quizzes!• Nope, it’s for your own good

• Brian and I will slow down the demos in lecture

Page 19: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!• Nope, it’s for your own good

• Have two midterms instead of quizzes!• Nope, it’s for your own good

• Brian and I will slow down the demos in lecture• When we can

Page 20: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!• Nope, it’s for your own good

• Have two midterms instead of quizzes!• Nope, it’s for your own good

• Brian and I will slow down the demos in lecture• When we can

• Brian’s office hours are great

Page 21: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!• Nope, it’s for your own good

• Have two midterms instead of quizzes!• Nope, it’s for your own good

• Brian and I will slow down the demos in lecture• When we can

• Brian’s office hours are great• Some administrative things are out of our control

Page 22: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More Survey Responses

• Remove the auto-grader delay on projects!• Nope, it’s for your own good

• Have two midterms instead of quizzes!• Nope, it’s for your own good

• Brian and I will slow down the demos in lecture• When we can

• Brian’s office hours are great• Some administrative things are out of our control• 1/6 students came to the potluck, 5/6 want

another one

Page 23: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Roadmap

Introduction

Functions

Data

Mutability

Objects

Interpretation

Paradigms

Applications

Page 24: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Roadmap

• This week (Objects), the goals are:

Introduction

Functions

Data

Mutability

Objects

Interpretation

Paradigms

Applications

Page 25: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Roadmap

• This week (Objects), the goals are:• To learn the paradigm of

object-oriented programming

Introduction

Functions

Data

Mutability

Objects

Interpretation

Paradigms

Applications

Page 26: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Roadmap

• This week (Objects), the goals are:• To learn the paradigm of

object-oriented programming

• To study applications of, and problems that be solved using, OOP

Introduction

Functions

Data

Mutability

Objects

Interpretation

Paradigms

Applications

Page 27: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance

Page 28: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance

• Powerful idea in Object-Oriented Programming

Page 29: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance

• Powerful idea in Object-Oriented Programming• Way of relating similar classes together

Page 30: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance

• Powerful idea in Object-Oriented Programming• Way of relating similar classes together• Common use: a specialized class inherits from a

more general class

Page 31: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance

• Powerful idea in Object-Oriented Programming• Way of relating similar classes together• Common use: a specialized class inherits from a

more general class

class <new class>(<base class>): ...

Page 32: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance

• Powerful idea in Object-Oriented Programming• Way of relating similar classes together• Common use: a specialized class inherits from a

more general class

class <new class>(<base class>): ...

• The new class shares attributes with the base class, and overrides certain attributes

Page 33: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance

• Powerful idea in Object-Oriented Programming• Way of relating similar classes together• Common use: a specialized class inherits from a

more general class

class <new class>(<base class>): ...

• The new class shares attributes with the base class, and overrides certain attributes

• Implementing the new class is now as simple as specifying how it’s different from the base class

Page 34: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

Page 35: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

Page 36: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

Page 37: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

Page 38: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

Page 39: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

Page 40: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

Page 41: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

Page 42: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

Page 43: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

Page 44: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

Page 45: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

Page 46: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

Page 47: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

Page 48: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

Page 49: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

Page 50: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

Page 51: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: thunder shock

Page 52: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: thunder shock

• Electric-type Pokémon can:

Page 53: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: thunder shock

• Electric-type Pokémon can:

• say their name

Page 54: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: thunder shock

• Electric-type Pokémon can:

• say their name

• attack and sometimes paralyze other Pokémon

Page 55: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: thunder shock

• Electric-type Pokémon can:

• say their name

• attack and sometimes paralyze other Pokémon

Page 56: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: thunder shock

• Electric-type Pokémon can:

• say their name

• attack and sometimes paralyze other Pokémon

Page 57: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Inheritance Example (demo)

class Pokemon: """A Pokemon.""" ...

• Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: tackle

• Pokémon can:

• say their name

• attack other Pokémon

class ElectricType(Pokemon): """An electric-type Pokemon.""" ...

• Electric-type Pokémon have:

• a name

• a trainer

• a level

• an amount of HP (life)

• a basic attack: thunder shock

• Electric-type Pokémon can:

• say their name

• attack and sometimes paralyze other Pokémon

Page 58: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

class ElectricType(Pokemon): basic_attack = 'thunder shock' prob = 0.1 def attack(self, other): Pokemon.attack(self, other) if random() < self.prob and type(other) != ElectricType: other.paralyzed = True print(other.name, 'is paralyzed!')

Designing for Inheritance

Page 59: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Don’t repeat yourself! Use existing implementations

class ElectricType(Pokemon): basic_attack = 'thunder shock' prob = 0.1 def attack(self, other): Pokemon.attack(self, other) if random() < self.prob and type(other) != ElectricType: other.paralyzed = True print(other.name, 'is paralyzed!')

Designing for Inheritance

Page 60: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Don’t repeat yourself! Use existing implementations• Reuse overridden attributes by accessing them through

the base class

class ElectricType(Pokemon): basic_attack = 'thunder shock' prob = 0.1 def attack(self, other): Pokemon.attack(self, other) if random() < self.prob and type(other) != ElectricType: other.paralyzed = True print(other.name, 'is paralyzed!')

Designing for Inheritance

Page 61: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Don’t repeat yourself! Use existing implementations• Reuse overridden attributes by accessing them through

the base class• Look up attributes on instances if possible

class ElectricType(Pokemon): basic_attack = 'thunder shock' prob = 0.1 def attack(self, other): Pokemon.attack(self, other) if random() < self.prob and type(other) != ElectricType: other.paralyzed = True print(other.name, 'is paralyzed!')

Designing for Inheritance

Page 62: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Don’t repeat yourself! Use existing implementations• Reuse overridden attributes by accessing them through

the base class• Look up attributes on instances if possible

class ElectricType(Pokemon): basic_attack = 'thunder shock' prob = 0.1 def attack(self, other): Pokemon.attack(self, other) if random() < self.prob and type(other) != ElectricType: other.paralyzed = True print(other.name, 'is paralyzed!')

Designing for Inheritance

Page 63: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Don’t repeat yourself! Use existing implementations• Reuse overridden attributes by accessing them through

the base class• Look up attributes on instances if possible

class ElectricType(Pokemon): basic_attack = 'thunder shock' prob = 0.1 def attack(self, other): Pokemon.attack(self, other) if random() < self.prob and type(other) != ElectricType: other.paralyzed = True print(other.name, 'is paralyzed!')

Designing for Inheritance

Page 64: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Don’t repeat yourself! Use existing implementations• Reuse overridden attributes by accessing them through

the base class• Look up attributes on instances if possible

class ElectricType(Pokemon): basic_attack = 'thunder shock' prob = 0.1 def attack(self, other): Pokemon.attack(self, other) if random() < self.prob and type(other) != ElectricType: other.paralyzed = True print(other.name, 'is paralyzed!')

Designing for Inheritance

Page 65: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance

Page 66: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance

• In Python, a class can inherit from multiple base classes

Page 67: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance

• In Python, a class can inherit from multiple base classes

• This exists in many but not all object-oriented languages

Page 68: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance

• In Python, a class can inherit from multiple base classes

• This exists in many but not all object-oriented languages

• This is a tricky and often dangerous subject, so proceed carefully!

Page 69: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance

• In Python, a class can inherit from multiple base classes

• This exists in many but not all object-oriented languages

• This is a tricky and often dangerous subject, so proceed carefully!

class FlyingType(Pokemon): basic_attack = 'peck' damage = 35 def fly(self, location): print(self.trainer, 'flew to', location)

Page 70: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

Page 71: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

• ZapdosisalegendarybirdPokémon

Page 72: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

• ZapdosisalegendarybirdPokémon

• Zapdos’attack,thunder,doesalotofdamage

Page 73: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

• ZapdosisalegendarybirdPokémon

• Zapdos’attack,thunder,doesalotofdamage

• Zapdoscanparalyzewhenattacking

Page 74: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

• ZapdosisalegendarybirdPokémon

• Zapdos’attack,thunder,doesalotofdamage

• Zapdoscanparalyzewhenattacking

• Zapdoscanfly

Page 75: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

• ZapdosisalegendarybirdPokémon

• Zapdos’attack,thunder,doesalotofdamage

• Zapdoscanparalyzewhenattacking

• Zapdoscanfly

• Zapdoscan’tsayitsownname

Page 76: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

• ZapdosisalegendarybirdPokémon

• Zapdos’attack,thunder,doesalotofdamage

• Zapdoscanparalyzewhenattacking

• Zapdoscanfly

• Zapdoscan’tsayitsownname

class Zapdos(ElectricType, FlyingType): basic_attack = 'thunder' damage = 120 def speak(self): print('EEEEEEEE')

Page 77: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

Zapdos

Pokemon

FlyingTypeElectricType

Page 78: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Multiple Inheritance Example

Zapdos

Pokemon

FlyingTypeElectricType

(demo)

Page 79: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More on Design

Page 80: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More on Design

• This example has been shortened for lecture purposes, and could have better design if done properly

Page 81: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More on Design

• This example has been shortened for lecture purposes, and could have better design if done properly

• We should create a class for every species of Pokémon

Page 82: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More on Design

• This example has been shortened for lecture purposes, and could have better design if done properly

• We should create a class for every species of Pokémon• Consequently, we should not create instances of the

Pokemon, ElectricType, or FlyingType classes

Page 83: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More on Design

• This example has been shortened for lecture purposes, and could have better design if done properly

• We should create a class for every species of Pokémon• Consequently, we should not create instances of the

Pokemon, ElectricType, or FlyingType classes

• We should create classes for different types of attacks, with damage and special effect attributes

Page 84: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More on Design

• This example has been shortened for lecture purposes, and could have better design if done properly

• We should create a class for every species of Pokémon• Consequently, we should not create instances of the

Pokemon, ElectricType, or FlyingType classes

• We should create classes for different types of attacks, with damage and special effect attributes• The relationship between classes that reference each

other (e.g., Pokemon and Tackle) is called composition

Page 85: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

More on Design

• This example has been shortened for lecture purposes, and could have better design if done properly

• We should create a class for every species of Pokémon• Consequently, we should not create instances of the

Pokemon, ElectricType, or FlyingType classes

• We should create classes for different types of attacks, with damage and special effect attributes• The relationship between classes that reference each

other (e.g., Pokemon and Tackle) is called composition

• Good design is a bigger topic in future classes

Page 86: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

Page 87: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

Page 88: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Page 89: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Page 90: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps

Page 91: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Page 92: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

Page 93: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

Page 94: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

Page 95: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

Half

Page 96: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

Halfsomeotherguy

Page 97: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

Half

HalfCousin

someotherguy

Page 98: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

Half

HalfCousin

someotherguy

Page 99: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

Half

HalfCousin

someotherguy

Page 100: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

HalfDouble

HalfCousin

someotherguy

Page 101: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

HalfDouble

HalfCousin

someotherguy

Double

Page 102: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

HalfDouble

HalfCousin

someotherguy DoubleHalfUncle

Double

Page 103: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

HalfDouble

HalfCousin

someotherguy DoubleHalfUncle

Double

Page 104: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

HalfDouble

HalfCousin

someotherguy DoubleHalfUncle

Double

Page 105: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

HalfDouble

HalfCousin

someotherguy DoubleHalfUncle

Page 106: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

HalfDouble

HalfCousin

someotherguy DoubleHalfUncle

Quadruple

Page 107: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Complicated Inheritance

To show how complicated inheritance can be, let’s look at an analogy through biological inheritance.

You

Mom Dad

Gramma Gramps GrandmomGrandpop

Aunt

someguy

HalfDouble

HalfCousin

someotherguy DoubleHalfUncle

Quadruple

Moral of the story: Inheritance, especially multiple inheritance, is complicated and weird. Use it carefully!

Page 108: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Raising and handling exceptions

Exceptions

Page 109: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

Page 110: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

Page 111: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

• Exceptions cause the program to halt immediately and print a stack trace if not handled

Page 112: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

• Exceptions cause the program to halt immediately and print a stack trace if not handled

• There are many different types of exceptions

Page 113: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

• Exceptions cause the program to halt immediately and print a stack trace if not handled

• There are many different types of exceptions

(demo)

Page 114: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

• Exceptions cause the program to halt immediately and print a stack trace if not handled

• There are many different types of exceptions

(demo)

>>> squareTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'square' is not defined

Page 115: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

• Exceptions cause the program to halt immediately and print a stack trace if not handled

• There are many different types of exceptions

(demo)

>>> squareTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'square' is not defined

stacktrace

Page 116: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

• Exceptions cause the program to halt immediately and print a stack trace if not handled

• There are many different types of exceptions

(demo)

>>> squareTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'square' is not defined

stacktrace

exceptiontype

Page 117: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

• Exceptions cause the program to halt immediately and print a stack trace if not handled

• There are many different types of exceptions

(demo)

>>> squareTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'square' is not defined

stacktrace

exceptiontype message

Page 118: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Exceptions

• In Python, exceptions alter the control flow of programs for exceptional circumstances, e.g., errors

• Exceptions cause the program to halt immediately and print a stack trace if not handled

• There are many different types of exceptions

(demo)

>>> squareTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'square' is not defined

stacktrace

exceptiontype message

linenumber

Page 119: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Raising Exceptions

Page 120: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Raising Exceptions

• We can cause an exception in our program by using the raise statement:

raise <expression>

Page 121: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Raising Exceptions

• We can cause an exception in our program by using the raise statement:

• <expression> must evaluate to either an exception class or instance

raise <expression>

Page 122: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Raising Exceptions

• We can cause an exception in our program by using the raise statement:

• <expression> must evaluate to either an exception class or instance• Otherwise, an error occurs…

raise <expression>

Page 123: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Raising Exceptions

• We can cause an exception in our program by using the raise statement:

• <expression> must evaluate to either an exception class or instance• Otherwise, an error occurs…

(demo)

raise <expression>

Page 124: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Raising Exceptions

• We can cause an exception in our program by using the raise statement:

• <expression> must evaluate to either an exception class or instance• Otherwise, an error occurs…

• An exception class is any class that inherits from the built-in BaseException class

(demo)

raise <expression>

Page 125: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Raising Exceptions

• We can cause an exception in our program by using the raise statement:

• <expression> must evaluate to either an exception class or instance• Otherwise, an error occurs…

• An exception class is any class that inherits from the built-in BaseException class• Almost all built-in exceptions inherit from the

Exception class, which inherits from BaseException

(demo)

raise <expression>

Page 126: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

User-defined Exceptions

Page 127: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

User-defined Exceptions

• It’s possible to create our own exception types by defining a new class that inherits from Exception or a subclass of Exception

Page 128: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

User-defined Exceptions

• It’s possible to create our own exception types by defining a new class that inherits from Exception or a subclass of Exception

• These user-defined exceptions can then be used in raise statements, just like any other exception

Page 129: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

User-defined Exceptions

• It’s possible to create our own exception types by defining a new class that inherits from Exception or a subclass of Exception

• These user-defined exceptions can then be used in raise statements, just like any other exception

• There aren’t many reasons to create new exceptions, since Python already has so many

Page 130: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

User-defined Exceptions

• It’s possible to create our own exception types by defining a new class that inherits from Exception or a subclass of Exception

• These user-defined exceptions can then be used in raise statements, just like any other exception

• There aren’t many reasons to create new exceptions, since Python already has so many

class MySpecialException(Exception): def __init__(self, msg): # special magic

Page 131: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

User-defined Exceptions

• It’s possible to create our own exception types by defining a new class that inherits from Exception or a subclass of Exception

• These user-defined exceptions can then be used in raise statements, just like any other exception

• There aren’t many reasons to create new exceptions, since Python already has so many

raise MySpecialException('so special')

class MySpecialException(Exception): def __init__(self, msg): # special magic

Page 132: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Handling Exceptions

Page 133: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Handling Exceptions

• The try statement allows us to handle exceptions and continue running our program

Page 134: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Handling Exceptions

• The try statement allows us to handle exceptions and continue running our program

try: <try suite> except <exception type> as <name>: <except suite>

Page 135: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Handling Exceptions

• The try statement allows us to handle exceptions and continue running our program

try: <try suite> except <exception type> as <name>: <except suite>

Execution Rule for try Statements:

Page 136: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Handling Exceptions

• The try statement allows us to handle exceptions and continue running our program

try: <try suite> except <exception type> as <name>: <except suite>

Execution Rule for try Statements:

1. Execute the <try suite>.

Page 137: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Handling Exceptions

• The try statement allows us to handle exceptions and continue running our program

try: <try suite> except <exception type> as <name>: <except suite>

Execution Rule for try Statements:

1. Execute the <try suite>.

2. If an exception of <exception type> is raised, switch to executing the <except suite> with <name> bound to the exception that was raised.

Page 138: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Handling Exceptions

• The try statement allows us to handle exceptions and continue running our program

try: <try suite> except <exception type> as <name>: <except suite>

Execution Rule for try Statements:

1. Execute the <try suite>.

2. If an exception of <exception type> is raised, switch to executing the <except suite> with <name> bound to the exception that was raised.

(demo)

Page 139: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python protocols and magic methods

Interfaces

Page 140: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Interfaces

Page 141: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Interfaces

• Computer science often involves communication between different components

Page 142: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Interfaces

• Computer science often involves communication between different components• Communication between the program and the user, between

two different programs, between two objects in the same program, etc.

Page 143: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Interfaces

• Computer science often involves communication between different components• Communication between the program and the user, between

two different programs, between two objects in the same program, etc.

• This can get very complicated, since these components often have different behaviors and specifications

Page 144: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Interfaces

• Computer science often involves communication between different components• Communication between the program and the user, between

two different programs, between two objects in the same program, etc.

• This can get very complicated, since these components often have different behaviors and specifications

• Interfaces specify rules for communication between these components, and this is a form of abstraction!

Page 145: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Interfaces

• Computer science often involves communication between different components• Communication between the program and the user, between

two different programs, between two objects in the same program, etc.

• This can get very complicated, since these components often have different behaviors and specifications

• Interfaces specify rules for communication between these components, and this is a form of abstraction!• E.g., to use an object, we don’t need to know how it is

implemented if we know the interface for the object

Page 146: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Interfaces

• Computer science often involves communication between different components• Communication between the program and the user, between

two different programs, between two objects in the same program, etc.

• This can get very complicated, since these components often have different behaviors and specifications

• Interfaces specify rules for communication between these components, and this is a form of abstraction!• E.g., to use an object, we don’t need to know how it is

implemented if we know the interface for the object• There are several common interfaces that are widely used

in Python, called protocols

Page 147: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python Object Interfaces

Page 148: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python Object Interfaces

• In Python, object interfaces are usually implemented through magic methods

Page 149: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python Object Interfaces

• In Python, object interfaces are usually implemented through magic methods• Special methods surrounded by double underscores

(e.g., __init__) that add “magic” to your classes

Page 150: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python Object Interfaces

• In Python, object interfaces are usually implemented through magic methods• Special methods surrounded by double underscores

(e.g., __init__) that add “magic” to your classes

• We will look at two examples of these interfaces:

Page 151: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python Object Interfaces

• In Python, object interfaces are usually implemented through magic methods• Special methods surrounded by double underscores

(e.g., __init__) that add “magic” to your classes

• We will look at two examples of these interfaces:• The arithmetic interface

Page 152: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python Object Interfaces

• In Python, object interfaces are usually implemented through magic methods• Special methods surrounded by double underscores

(e.g., __init__) that add “magic” to your classes

• We will look at two examples of these interfaces:• The arithmetic interface• The (mutable) container protocol

Page 153: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python Object Interfaces

• In Python, object interfaces are usually implemented through magic methods• Special methods surrounded by double underscores

(e.g., __init__) that add “magic” to your classes

• We will look at two examples of these interfaces:• The arithmetic interface• The (mutable) container protocol

• For more information, see:http://www.rafekettler.com/magicmethods.html

Page 154: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Python Object Interfaces

• In Python, object interfaces are usually implemented through magic methods• Special methods surrounded by double underscores

(e.g., __init__) that add “magic” to your classes

• We will look at two examples of these interfaces:• The arithmetic interface• The (mutable) container protocol

• For more information, see:http://www.rafekettler.com/magicmethods.html

(demo)

Page 155: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Custom Containers

Page 156: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Python has many built-in container types: lists, tuples, ranges, dictionaries, etc.

Custom Containers

Page 157: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Python has many built-in container types: lists, tuples, ranges, dictionaries, etc.

• Python also has a protocol for defining custom container classes

Custom Containers

Page 158: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Python has many built-in container types: lists, tuples, ranges, dictionaries, etc.

• Python also has a protocol for defining custom container classes

• Defining custom containers is as easy as implementing the __len__, __getitem__, and __contains__ magic methods

Custom Containers

Page 159: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Python has many built-in container types: lists, tuples, ranges, dictionaries, etc.

• Python also has a protocol for defining custom container classes

• Defining custom containers is as easy as implementing the __len__, __getitem__, and __contains__ magic methods

• __len__ is called by len, __getitem__ is used in indexing, and __contains__ is used in membership

Custom Containers

Page 160: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Python has many built-in container types: lists, tuples, ranges, dictionaries, etc.

• Python also has a protocol for defining custom container classes

• Defining custom containers is as easy as implementing the __len__, __getitem__, and __contains__ magic methods

• __len__ is called by len, __getitem__ is used in indexing, and __contains__ is used in membership

• To create a mutable container, we can also implement the __setitem__ and __delitem__ methods

Custom Containers

Page 161: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

• Python has many built-in container types: lists, tuples, ranges, dictionaries, etc.

• Python also has a protocol for defining custom container classes

• Defining custom containers is as easy as implementing the __len__, __getitem__, and __contains__ magic methods

• __len__ is called by len, __getitem__ is used in indexing, and __contains__ is used in membership

• To create a mutable container, we can also implement the __setitem__ and __delitem__ methods

Custom Containers (demo)

Page 162: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Summary

Page 163: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Summary

• Inheritance allows us to implement relationships between classes and simplify our programs

Page 164: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Summary

• Inheritance allows us to implement relationships between classes and simplify our programs

• Interfaces allow for standardized interaction between different components by defining rules for communication

Page 165: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Summary

• Inheritance allows us to implement relationships between classes and simplify our programs

• Interfaces allow for standardized interaction between different components by defining rules for communication• Implementing interfaces in Python can allow our

custom classes to behave like built-in classes

Page 166: 16-Object-Oriented Programming IIcs61a/su16/assets/... · Inheritance • Powerful idea in Object-Oriented Programming • Way of relating similar classes together • Common use:

Summary

• Inheritance allows us to implement relationships between classes and simplify our programs

• Interfaces allow for standardized interaction between different components by defining rules for communication• Implementing interfaces in Python can allow our

custom classes to behave like built-in classes

• Both are tools for abstraction, and learning them well is one of the keys to becoming a great object-oriented programmer