Download presentation
Presentation is loading. Please wait.
Published byΑθανάσιος Ιωάννου Modified over 5 years ago
1
Terry Scott University of Northern Colorado 2007 Prentice Hall
Object-Oriented Programming in Python Goldwasser and Letscher Chapter 9 Inheritance Terry Scott University of Northern Colorado 2007 Prentice Hall
2
Introduction: Chapter 9 Topics
Augmentation. Specialization. Inheritance why and terminology. is-a and has-a relationships (inheritance and composition). When should inheritance not be used. Class Hierarchies and cs1graphics. Multiple inheritance. Case Study: Mailbox class.
3
Inheritance: Why and Terminology
Inheritance facilitates code reuse. Original class is called base or parent class. Inherited class is called a derived or child class. Augmenting: Child class adds a new method that wasn't present in the parent class. Specializing: Child class overrides or changes a method that was originally defined in the parent class.
4
Augmentation Child class adds functionality to parent class.
Create a DeluxeTV class that inherits from the Television class. DeluxeTV class adds (augments) favorite channels attribute and methods to manipulate it to base Television class.
5
DeluxeTV Class Code from Television import Television
def DeluxeTV(Television) """TV that maintains a set of favorite channels""" def __init__(self): """call the base class Television to initialize the DeluxeTV also""" Television.__init__(self): self._favorites = [ ]
6
DeluxeTV (continued) def addToFavorites(self):
"""Add current channel to favorites""" if self._powerOn and self._channel not in self._favorites: self._favorites.append(self._channel) def removeFromFavorites(self): """Remove current channel from favorites""" if self._powerOn and self._channel in self._favorites: self._favorites.remove(self._channel)
7
DeluxeTV (continued) def jumpToFavorite(self):
"""Jumps to next higher channel in favorites. If none higher then it wraps to lower and no favorites remains the same""" if self._powerOn and len(self._favorites) > 0: closest = max(self._channel) if closest <= self._channel: closest = min(self._favorites) else: for option in self._favorites: closest = option self.setChannel(closest) return closest
8
Specialization Augmentation adds new functionality.
Specialization changes parent method so the child class does some new operation. DeluxeTV class jumpToFavorite method was difficult to do because list was not sorted. Create a new data type called: SortedSet(list). Notice SortedSet is a child (derived) class of list. It will be similar to a list but items will be in sorted order. Use this set to simplify DeluxeTV class.
9
SortedSet Methods def indexAfter(self, value):
"""Places value in list in sorted order""" walk = 0 while walk < len(self) and value >= self[walk]: walk += 1 return walk def insert(self, value): """check to see if item is not in list and places in sorted order using indexAfter method" if value not in self: place = self.indexAfter(value) list insert(self.place, value)
10
SortedSet Using the list class as the base class for SortedSet has disadvantages. Some list methods should not be available in the SortedSet. This can be accomplished by either preventing access or converting them so that they place items in sorted order. append, extend, sort, +, index, remove reverse, pop, in, indexing [ ], len, ==. <, str
11
SortedSet Code: Preventing or Changing Some List Methods
def append(self, object): self.insert(object) #remember insert puts object in order def extend(self, other): for element in other: self.insert(element) #places elements in sorted order def sort(self): pass #called a NOP (no operation) in some languages def index(self, value): return self._items.index(value)
12
SortedSet Code (continued)
def __add__(self, other): result = SortedSet(self) #combines lists so they result.extend(other) #remain in sorted sorted order. return result def remove(self, element): self._items.remove(element) def pop(self, index=None): return self._items.pop(index)
13
SortedSet Code (continued)
def __contains__(self,element): return element in self._items def __getitem__(self, index): return self._items[index] def __len__(self): return len(self._items)
14
SortedSet Code (continued)
def __eq__(self, other): return self._items == other._items def __lt__(self, other): return self._items < other._items def __str__(self): return str(self._items)
15
SortedSet Code (continued)
def reverse(self): raise RuntimeError('SortedSet cannot be reversed') def __setitem__(self, index, object): raise RuntimeError('Syntax not supported by SortedSet')
16
DeluxeTV Using SortedSet to Implement jumpToFavorite(self)
def jumpToFavorite(self): if self._powerOn and len(self._favorites)>0 resultindex = self._favorites.indexAfter(self.channel) result = self._favorties[0] else: result = self._favorites[resultIndex] self.setChannel(result) return result
17
Inheritance Versus Composition
Inheritance is described as: is-a relationship Composition is described as: has-a relationship Can use list as composition rather than inheritance in the SortedSet class. SortedSet has-a list. Maybe easier since unneeded or problem methods do not need to be overridden.
18
SortedSet Class Using list Class with Composition
class SortedSet: def __init__(self): self._items = list() The rest of the class proceeds using self._items to store the list. Consult code on pages in book.
19
Star Class in cs1graphics
Make a new class Star that inherits from Polygon class Star(Polygon) Star instance medal = Star(5) paper.add(medal)
20
Star Class Code class Star(Polygon):
def __init__(self, numRays=5, outerRadius=10, innerRatio=5, center= Point(0,0)): Polygon.__init__(self) #call parent constructor top=Point(0, -outerRadius) #top point above origin angle = 180.0/numRays for i in range(numRays): self.addPoint(top^(angle* (2 * i))) #rotate point self.addPoint(innerRatio * top ^(angle * (2*I + 1))) self.adjustReference(0, outerRadius) self.move(center.getX(), center.getY()) self._innerRatio = innerRatio
21
Star Class Code (continued)
def setInnerRatio(self, newRatio): factor = newRatio / self._innerRatio self._innerRatio = newRatio for i in range(1,self.getNumberOfPoints(),2): self.setPoint(factor * self.getPoint(i),i):
22
Square Class Illustrate inheritance once more but this time with the Square class. Square class inherits from the rectangle class. setWidth and setHeight both call setSize which makes width and height the same.
23
Square Class Code class Square(Rectangle):
def __init__(self.size = 10, center = None): Rectangle __init__(self, size, size, center) def setWidth(self, width): self.setSize(width) def setHeight(self, height): Rectangle.setWidth(self, size) def setSize(self, size): Rectangle.setHeight(self, size) def getSize(self): return self.getWidth()
24
Car Class Inheritance Have car class inherit from layer
Car can now have attributes of layer and can add methods required for the car class.
25
Car Class Code class Car(Layer): #Car inherits from Layer
def __init__(self, bodyColor='blue'): Layer.__init__(self) tire1 = Circle(10, Point(-20,-10) tire1.setFillColor('black') self.add(tire1) tire2 = Circle(10, Point(20, -10)) tire2.setFillColor('black') self.add(tire2) self._body = Rectangle(70,30, Point(0,-25)) self._body.setFillColor(bodyColor) self.body.setDepth(60) self.add(self._body)
26
Car Class Code (Continued)
def setBodyColor(self, bodyColor): self._body.setFillColor(bodyColor)
27
Car Class Alternative Implementation
Problem with using Layer as the base class for the Car class. The add, remove, and clear methods could be used to alter a car object by the user of the class. A solution is to have the car class inherit from the Drawable class. _draw is a method in the Drawable class.
28
Class Car Code class Car(Drawable):
def __init__(self, bodyColor= 'blue') Drawable.__init__(self) #call parent constructor self._tire1 = Circle(10, Point(-20, -10) self.tire1.setFillColor('black') self._tire2 = Circle(10, Point(-20, -10) self.tire2.setFillColor('black') self.body = Rectangle(70, 30, Point(0,-25)) self.body.setFillColor(bodyColor)
29
Class Car Code (continued)
def setBodyColor(self, bodyColor): self._body.setFillColor(bodyColor) def _draw(self): self.beginDraw( ) #required protocol self._body._draw() self._tire1._draw() self._tire2._draw() self._completeDraw( ) #required protocol
30
Multiple Inheritance So far classes have only inherited from one class. Called single inheritance. Multiple inheritance: Can inherit from more than one class. Layer uses multiple inheritance: from Drawable and _GraphicsContainer. Canvas: single inheritance.
31
Layer Inheritance
32
Layer Class Code class Layer(Drawable, _GraphicsContainer):
def __init__(self): Drawable.__init__(self): #initialize both base _GraphicsContainer.__init__(self) #classes def __draw(self): self._beginDraw() for shape in self.getContents(): shape._draw() self._completeDraw()
33
LabeledRectangle Class
Class creates a rectangle. Places text centered in the rectangle. Inherit from classes Rectangle and Text.
34
LabeledRectangle Class Code
class LabeledRectangle(Text, Rectangle): def __init__(self, message) Text.__init__(self, message) Rectangle.__init__(self, width, height) self.setFillColor('white') def _draw(self): self._beginDraw() Rectangle._draw(self) Text._draw(self) self._completeDraw()
35
Mailbox Class Creating a new class. Decide on its properties and its actions. A Mailbox class properties: flag. door. A Mailbox actions: door open. door close. flag up. flag down.
36
Mailbox Below are possible configurations of the mailbox.
Consult book pages 323 – 325 for the code.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.