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

72
Slides modified from originals by Terry Scott University of Northern Inheritance and Management of Obj Text Chapter 9 and 10

description

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. - PowerPoint PPT Presentation

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

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

Inheritance and Management of ObjectsText Chapter 9 and 102Introduction: Chapter 9 TopicsAugmentation.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.3Inheritance: Why and TerminologyInheritance 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

Class diagram example

http://atlas.kennesaw.edu/~dbraun/csis4650/A%26D/UML_tutorial/class.htmMany orders, 1 customer (many to 1 relationship)Triangle shaped arrow indicates generalization. Customer is generalization of corporate customer and of personal customer.Corporate customer and personal customer inherit from customer45AugmentationChild class adds functionality to parent class.Remind and BillForMonth methods for the Corporate CustomerAnother 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.

6DeluxeTV Class Codefrom Television import Televisiondef 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 = [ ]

7DeluxeTV (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)8DeluxeTV (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[walk]:walk += 1 return walkdef 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)Quick spot check:Assume the list is [3,5,10,15]Add 12Add 1011SortedSetUsing 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, removereverse, pop, in, indexing [ ], len, ==. 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 resultAlternative formulationInstead 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. Differences in approachRefining List to be a SortedSetSortedSet inherits all of the characteristics of ListSortedSet isA ListisA 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 classCreating a new data type, SortedSet, and using List internallySortedSet does not inherit the properties of List, because SortedSet is not a list.SortedSet hasA listImportant distinctions, often confused.Do not need to redefine unneeded or unwanted list methodsA list is part of the construction of SortedSet20SortedSet Class Using list Class with Compositionclass SortedSet: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.Spot CheckLeft side of roomExercise 9.1Right side of roomExercise 9.2

Work in pairs (or threes)Talk to each other and compare ideasRead the question you are not working on so that you can ask questions when the other side reportsOther examplesRead through the other examples based on the graphics material23Multiple InheritanceSo 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. Lets look at a different one or twoSimple Inheritancefrom:http://www.gidnetwork.com/b-137.html>>>class FirstClass: #define the superclassdef setdata(self, value): #define methodsself.data = value #self refers to an instancedef display(self):print self.data>>>class SecondClass(FirstClass):#inherits from FirstClassdef display(self): #redefines displayprint 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 = 42Multiple InheritanceA newly defined class may inherit from more than one parentA person might be a student and an athlete, for exampleBook example: layer inherits from Drawable and _GraphicsContainer26Layer Inheritance

27Layer Class Codeclass 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()28LabeledRectangle ClassClass creates a rectangle.Places text centered in the rectangle.Inherit from classes Rectangle and Text. 29LabeledRectangle Class Codeclass 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()30Mailbox ClassCreating 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.31MailboxBelow are possible configurations of the mailbox. Consult book pages 323 325 for the code.Another set of code examples to review32Chapter 10 TopicsUnderstanding objects and references.Objects that reference other objects.Objects in connection with a function. Parameter passing.33Object Versus a Reference to the ObjectmySavings = 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.34Multiple References to the Same Object.myDebt = myCheckingThis 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.

35Diagram Showing References to Account Objects. myChecking and myDebt Are Aliases

36Equivalence Testinga == 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 is b 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. 37Garbage CollectionStarting with this situation

38Garbage Collection (continued)If you make this assignment myChecking = Account()The setup will now look like this:

This creates a new instance of Account39Garbage Collection (continued)Doing the following assignment: mySavings = Account()The situation looks like this:

Another new instanceWe no longer have any way to reference this instance of AccountGarbage Collection is the inelegant term used for cleaning up unreachable elements in a running program40Garbage 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.41Primitive Types>>> grades = ['A','B','C']>>> alphabet = ['A','B','C']id(object) returns the address of objectid(grades) and id(alphabet) give different values indicating that they are different lists.>>> hello = 'aloha'>>> goodbye = 'aloha'id(hello) and id(goodbye) have same valuesWhy? 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 memorySpot checkRight side of room do 10.1Left side of room do 10.2Also draw the diagram of the final configuration

Work in pairsBe sure to read the other question43Objects That Reference Other ObjectsA list object consists of items which are really references to other objects. This is pictured below:

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

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

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

47Deeper 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.

49Deeper 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.

50Advanced ModelingChapter 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. 51Copying ObjectsShallow copy a new reference whose attributes reference the same objects as the original.Deep copy a new reference whose attributes reference new objects.It is possible to have an object that has both shallow and deep copies.52Copying a Listdata is a list of points. Make a copy of data before the points are normalized.the following attempt is flawed. It only makes a shallow copy.

backup = list(data)for p in data: p.normalize()

The original data has its points also normalized. 53Copying a List (continued)Here is a way to solve the previous problem.

backup = [ ]for p in data: newP = Point(p.getX(), p.getY()) backup.append(newP) p.normalize() 54Copy ModuleTwo methods in the copy modulecopy(x) #makes a shallow copy of x.deepcopy(x) #makes a deep copy of x.Making a shallow copy of deluxeTV causes two different TV's to have the same underlying objects. This is okay when the objects are mutable but the _favorites list is the same for both objects.55DeluxeTV Diagram

Call byTraditional ways to communicate values between a calling program and a called programCall by nameObsolete. Copy the argument string wherever the parameter appears on the function. Very flexible, very dangerous. Essentially a macro expansion.Call by referenceArgument and parameter refer to the same memory location. Whatever happens in the function happens to the variable used in the call.Call by valueA copy of the value of the variable at the time of the call is passed to the function. The original value is not affected by any changes that occur in the function.Spot checkLeft side of room: 10.7Right side of room: 10.8

Work in pairsRead the other question58Objects in the Context of a FunctionInformation passing.formal parameters.actual parameters.In Python parameter passing uses standard assignment semantics.What effect that has depends on whether the parameter is mutable or immutable.59Objects in the Context of a Function (continued)When assignment is done from actual to formal parameters, the formal parameter receives the same reference as the actual parameter.If the actual parameter object is immutable, then any changes that occur to the formal parameter will change its reference and consequently the actual parameter will keep its original value. 60Objects in the Context of a Function (continued)However if the actual parameter is mutable, then changes that occur in the function will not change the reference value and consequently values will transmitted back to the actual argument.So: mutable objects effectively are passed by reference.Immutable objects are passed by value.Parameters and ArgumentsNote: book uses formal parameter and actual parameter and sometimes actual argument. More usual: function is defined with parameters and called with arguments.

62Illustrating Object Parametersdef verifyBalance(account, threshold):Check whether the balance of the given account meets a threshold meetsThreshold = account.getBalance() >= thresholdreturn meetsThreshold

claimedAssets = 200.0qualifies = verifyBalance(mySavings, claimedAssets)

#Actual parameters are assigned to formal parametersaccount = mySavingsthreshold = claimedAssets63Parameter Passingthreshold = 2 * threshold#float is immutable so new reference created#so original claimed Assets no longer points to#the same memory location.

Subtle!Float is immutable.If we assign a new value to a float, we get a new copy, with the same name, and the new value. So, it looks like float is mutable in practiceHowever, if we send a float to a function and the function changes the value, the new copy is local to the function. The original value is not changed.65Optional Parametersdef countdown(start = 10): for count in range(start,0,-1): print count

If countdown is called without a parameter, start takes the value 10.The optional parameter is assigned when the function is defined.

def pop(self, index = len(self)-1):#Doesn't work because self not defined when function defined.

66Optional Parameters (continued)Can do the following optional parameter for pop that will work.def pop(self, index = None):if index is None:index = len(self) 1#do rest of code for pop67Optional Parameters (continued)Use immutable types for optional parameters.Example problem using a list for an optional parameter.def __init__(self, favorites = [ ])Television.__init__(self)self._favorites = favorites68Optional Parameters (continued)The code on previous slide has a problem. Because the optional parameter is a list it is passed as a reference.Creating two instances of the DeluxeTV both will point to the same favorites list if no initial list is specified.Adding favorite channels to one also adds for the other TV object since they point to the same mutable list.69Intentional Aliasing of Colors#set both trees to have green leavesseasonColor = Color('green')leavesA.setFillColor(seasonColor)leavesB.setFillColor(seasonColor)

#change both trees' leaves to orangeraw_input('Press return to change seasons. ')seasonColor.setByName('orange')

#change one tree's leaves to yellow.raw_input('Press return to change right tree.)leavesB.setFillColor('yellow') #changes one#see next two slides for diagrams of what occurs.70First Color ChangeBoth trees foliage are changed.

71Second Color ChangeOnly one tree's color is changed.

Spot checkAll: 10.11