1 / 72

Slides modified from originals by Terry Scott University of Northern Colorado 2007 Prentice Hall

Inheritance and Management of Objects. Text Chapter 9 and 10. Slides modified from originals by Terry Scott University of Northern Colorado 2007 Prentice Hall. Introduction: Chapter 9 Topics. Augmentation. Specialization. Inheritance why and terminology.

aggie
Download Presentation

Slides modified from originals by Terry Scott University of Northern Colorado 2007 Prentice Hall

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Inheritance and Management of Objects Text Chapter 9 and 10 Slides modified from originals by 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. • We introduced these ideas in the first week of the semester 

  4. Class diagram example http://atlas.kennesaw.edu/~dbraun/csis4650/A%26D/UML_tutorial/class.htm

  5. Augmentation • Child class adds functionality to parent class. • Remind and BillForMonth methods for the Corporate Customer • Another example: • 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.

  6. 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 = [ ]

  7. DeluxeTV (continued) defaddToFavorites(self): """Add current channel to favorites""" if self._powerOnandself._channelnot in self._favorites: self._favorites.append(self._channel) defremoveFromFavorites(self): """Remove current channel from favorites""" if self._powerOnandself._channel in self._favorites: self._favorites.remove(self._channel)

  8. DeluxeTV (continued) defjumpToFavorite(self): """Jumps to next higher channel in favorites. If none higher then it wraps to lower and no favorites remains the same""" ifself._powerOnandlen(self._favorites) > 0: closest = max(self._channel) if closest <= self._channel: closest = min(self._favorites) else: for option inself._favorites: closest = option self.setChannel(closest) return closest This does not work OK to look at the idea, but do not trust the code

  9. 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.

  10. SortedSet Methods defindexAfter(self, value): """Places value in list in sorted order""" walk = 0 while walk < len(self) and value >= self[walk]: walk += 1 return walk definsert(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) Quick spot check: Assume the list is [3,5,10,15] Add 12 Add 10

  11. 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

  12. SortedSet Code: Preventing or Changing Some List Methods defappend(self, object): self.insert(object) #remember insert puts object in order defextend(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 defindex(self, value): return self._items.index(value) Redefining existing methods so that the regular ones will not work on the sorted list

  13. 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)

  14. 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)

  15. 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) Perhaps not all of them needed to be redefined? Doing them all makes certain that nothing is missed.

  16. SortedSet Code (continued) def reverse(self): raise RuntimeError('SortedSet cannot be reversed') def __setitem__(self, index, object): raise RuntimeError('Syntax not supported by SortedSet') We would not have defined these if creating SortedSet from scratch. Only the connection to List makes them necessary

  17. DeluxeTV Using SortedSet to Implement jumpToFavorite(self) def jumpToFavorite(self): if self._powerOnandlen(self._favorites)>0 resultindex = self._favorites.indexAfter(self.channel) if resultindex == len(self_favorites): result = self._favorties[0] # wrap around else: result = self._favorites[resultIndex] self.setChannel(result) return result

  18. Alternative formulation • Instead of creating SortedSet as a child class of list and redefining the list methods, we could create a new class and use the list data type internally to hold the values. • Then SortedSet is not a list. It is a new type. The new type is implemented using the existing list type, but the user does not see that.

  19. Differences in approach • Refining List to be a SortedSet • SortedSet inherits all of the characteristics of List • SortedSetisA List • isA is a property that says that the derived class has all the properties of the parent class, because it is a version of the parent class • Creating a new data type, SortedSet, and using List internally • SortedSet does not inherit the properties of List, because SortedSet is not a list. • SortedSethasA list Do not need to redefine unneeded or unwanted list methods • A list is part of the construction of SortedSet Important distinctions, often confused.

  20. SortedSet Class Using list Class with Composition classSortedSet: def __init__(self): self._items = list() • The rest of the class proceeds using self._items to store the list. • Consult code on pages 309-310 in book. Now, we define exactly the methods that we want. We do not have to worry about an inappropriate use of the list class methods.

  21. Spot Check • Left side of room • Exercise 9.1 • Right side of room • Exercise 9.2 • Work in pairs (or threes) • Talk to each other and compare ideas • Read the question you are not working on so that you can ask questions when the other side reports

  22. Other examples • Read through the other examples based on the graphics material

  23. Multiple Inheritance • So far classes have only inherited from one class. Called single inheritance. • Multiple inheritance: Can inherit from more than one class. • Several examples in the book. • Let’s look at a different one or two

  24. Simple Inheritance >>>class FirstClass: #define the superclass … def setdata(self, value): #define methods … self.data = value #’self’ refers to an instance … def display(self): … print self.data >>>class SecondClass(FirstClass): #inherits from FirstClass … def display(self): #redefines ‘display’ … print “Current value = ‘%s’” % self.data … >>>x=FirstClass() #instance of FirstClass >>>y=SecondClass() #instance of SecondClass >>>x.setdata(“The boy called Brian.”) >>>y.setdata(42) >>>x.display() The boy called Brian. >>>y.display() Current value = ‘42’ from:http://www.gidnetwork.com/b-137.html

  25. Multiple Inheritance • A newly defined class may inherit from more than one parent • A person might be a student and an athlete, for example • Book example: layer inherits from Drawable and _GraphicsContainer

  26. Layer Inheritance

  27. 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()

  28. LabeledRectangle Class • Class creates a rectangle. • Places text centered in the rectangle. • Inherit from classes Rectangle and Text.

  29. LabeledRectangle Class Code classLabeledRectangle(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()

  30. 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.

  31. Mailbox • Below are possible configurations of the mailbox. • Consult book pages 323 – 325 for the code. Another set of code examples to review

  32. Chapter 10 Topics • Understanding objects and references. • Objects that reference other objects. • Objects in connection with a function. • Parameter passing.

  33. Object Versus a Reference to the Object • mySavings = Account() • Previously the identifier mySavings was seen as the actual Account or at least a tag on the Account object. • mySavings is really a memory location that has the address of the Account object. This is called a pointer.

  34. Multiple References to the Same Object. • myDebt = myChecking • This makes another reference to the previously created Account object. • id(myDebt) will return the address of myDebt and will be equal to id(myChecking). • myDebt and myChecking are aliases. • Changing the balance in myChecking also changes balance in myDebt.

  35. Diagram Showing References to Account Objects.myCheckingand myDebt Are Aliases

  36. Equivalence Testing • a == b True if a and b are equivalent. • What does equivalent mean? • If a and b are aliases that is one kind of equivalence. • If a and b are bank accounts they might be considered equivalent if they have the same account balance. • a isb will be True only when a and b are aliases. • a == b will be True when the values for a and b are the same.

  37. Garbage Collection Starting with this situation

  38. Garbage Collection (continued) If you make this assignment myChecking = Account() The setup will now look like this: This creates a new instance of Account

  39. Garbage Collection (continued) Doing the following assignment: mySavings = Account() The situation looks like this: Another new instance We no longer have any way to reference this instance of Account Garbage Collection is the inelegant term used for cleaning up unreachable elements in a running program

  40. Garbage Collection (continued) • The account object that is pictured in the upper left on the previous slide no longer can be reached. There is nothing referencing that object. • The memory for that unreferenced account object should be returned to the free memory pool so it can be used for other objects. • This is handled by Python using reference counts. The reference count is the number of pointers to an object. • Once the reference count for an object falls to zero then the object memory is returned to free memory pool so that it may be reused.

  41. Primitive Types >>> grades = ['A','B','C'] >>> alphabet = ['A','B','C'] id(object) returns the address of object id(grades) and id(alphabet) give different values indicating that they are different lists. >>> hello = 'aloha' >>> goodbye = 'aloha' id(hello) and id(goodbye) have same values • Why? The str type is immutable so there is no harm in making these the same reference. The advantage is that it saves memory. This is something the Python interpreter does as an optimization. Since it causes no harm, it is a good way to save some memory

  42. Spot check • Right side of room do 10.1 • Left side of room do 10.2 • Also draw the diagram of the final configuration • Work in pairs • Be sure to read the other question

  43. Objects That Reference Other Objects • A list object consists of items which are really references to other objects. • This is pictured below:

  44. Objects Referencing Other Objects The diagram below illustrates a more accurate picture of the Deluxe TV showing references to references to references.

  45. Objects Referencing Other Objects • Even though frozenAssets refers to a tuple that is immutable. • However, the objects the tuple point to are Account objects which are mutable.

  46. Deeper Forms of AliasingSame Portfolios >>> spouseAssets = myAssets • Representation for spouses that have a single portfolio that are shared accounts.

  47. Deeper Forms of Aliasing (continued) • Adding a new account to the list will add that account for both myAssets and spouseAssets.

  48. Deeper Forms of Aliasing (continued) • Different portfolios with common accounts.

  49. Deeper Forms of Aliasing (continued) • Adding a new account to the spouseAssets. • Use spouseAssets.append(spouseRetirement). • Notice the spouseAssets has shared accounts with myAccounts but it has an additional account called spouseRetirement.

  50. Advanced Modeling • Chapter 1 student registration system. • Course instructor teaches two different courses • instructor attribute for each course should reference the same instructor object. • Each student should have a separate schedule even if they have the same classes. • One student can change their schedule without changing the other student's schedule.

More Related