Unformatted text preview:

6.01, Spring Semester, 2008—Course notes for Week 4 1MASSACHVSETTS INSTITVTE OF TECHNOLOGYDepartment of Electrical Engineering and Computer Science6.01—Introduction to EECS ISpring Semester, 2008Course notes for Week 41 State, objects, and abstractionLast week we introduced object-oriented programming, motivating classes because they provide aconvenient way of organizing the procedures and data associated with an abstract data type. Thisweek, we’ll look at some other important abstractions strategies for computer programs and seehow OOP can help us with them, as well.In the context of our table and the PCAP framework, we will pay special attention to genericfunctions and inheritance in OOP, which give us methods for capturing common patterns in data(and the procedures that operate on that data).Procedures DataPrimitives +, *, == numbers, stringsMeans of combination if, while, f(g(x)) lists, dictionaries, objectsMeans of abstraction def abstract data types, classesMeans of capturing common patterns higher-order procedures generic functions, inheritance1.1 Objects and stateWe saw, last week, how to define a convenient bank-account object that implements an ADT for abank account.class Account :def __ini t__ ( self , ini tialBal anc e ):self . c urr ent Bal anc e = ini tia lBalanc edef balance ( self ):return self . cu rre ntB ala ncedef deposit ( self , amount ):self . c urr ent Bal anc e = self . cu rrentBa lan ce + amountdef cre ditL imit ( self ):return min ( self . cu rre ntB ala nce * 0.5 , 10000000)We can use this ADT to create and manage several bank accounts at once:>>> a = Account (100)>>> b = Account (10 00000 )>>> Acco unt . bala nce (a)100>>> a. balance ()100>>> Acco unt . depo sit (a , 100)>>> a. deposit (100)6.01, Spring Semester, 2008—Course notes for Week 4 2>>> a. balance ()300>>> b. balance ()1000000>>> a. balance ()300The Account class contains the procedures that are common to all bank accounts; the individualobjects contain state in the values associated with the names in their environments. That state ispersistent, in the sense that it exists for the lifetime of the program that is running, and doesn’tdisappear when a particular method call is over.1.2 Generic functionsNow, imagine that the bank we’re running is getting bigger, and we want to have several differentkinds of accounts. Now there is a monthly fee just to have the account, and the credit limit dependson the account type. Let’s see how it would work to use dictionaries to store the data for our bankaccounts. Here’s a new data structure and two constructors for the different kinds of accounts.def ma ke Pre mie rA cco unt ( balance , rate , owner , ssn ):return {" balance ": balance ," in ter estR ate ": rate ," owner ": owner ," ssn ": ssn ," type " : " Premier "}def ma ke Eco nom yA cco unt ( balance , rate , owner , ssn ):return { " balance ": balance ," in ter estR ate ": rate ," owner ": owner ," ssn ": ssn ," type " : " Economy "}a5 = ma keP remie rAc co unt (3021835.97 , .0003 , " Susan Squeeze ", " 558421212 ")a6 = ma keE conom yAc co unt (3.22 , .00000001 , " Carl Co nstr icto r ", " 55 51213 48 ")The procedures for depositing and getting the balance would be the same for both kinds of accounts.But how would we get the credit limit? We could have separate procedures for getting the creditlimit for each different kind of account:def cr ed itL imi tE con omy ( account ):return min ( account [ ’ bala nce ’ ]*0.5 , 20.00)def cr ed itL imi tP rem ier ( account ):return min ( account [ ’ bala nce ’ ]*1.5 , 10 000000)>>> c red it Lim itPre mie r ( a5 )453 275 3. 955 000 00 01>>> c red it Lim itEco nom y ( a6 )1.6 100 00 000 000 00 01But doing this means that, no matter what you’re doing with this account, you have to be consciousof what kind of account it is. It would be nicer if we could treat the account generically. We can,6.01, Spring Semester, 2008—Course notes for Week 4 3by writing one procedure that does different things depending on the account type. This is calleda generic function.def cre ditL imit ( account ):if ac count [" type "] == " Economy ":return min ( balance *0.5 , 20.00)elif acco unt [" type "] == " Premier ":return min ( balance *1.5 , 10 000000)else :return min ( balance *0.5 , 10 000000)>>> cr editLim it ( a5 )453 275 3. 955 000 00 01>>> cr editLim it ( a6 )1.6 100 00 000 000 00 01In this example, we had to do what is known as type dispatching; that is, we had to explicitly checkthe type of the account being passed in and then do the appropriate operation. We’ll see later inthis lecture that Python has the ability to do this for us automatically.1.3 Classes and inheritanceIf we wanted to define another type of account as a Python class, we could do it this way:class Pre mie rAc cou nt :def __ini t__ ( self , ini tialBal anc e ):self . c urr ent Bal anc e = ini tia lBalanc edef balance ( self ):return self . cu rre ntB ala ncedef deposit ( self , amount ):self . c urr ent Bal anc e = self . curr entBala nce + amountdef cre ditL imit ( self ):return min ( self . cu rre ntB ala nce * 1.5 , 10000 000)>>> c = Pre mie rAc cou nt (1000)>>> c. creditL imit ()1500.0This will let people with premier accounts have larger credit limits. And, the nice thing is that wecan ask for its credit limit without knowing what kind of an account it is, so we see that objectssupport generic functions, as we spoke about them earlier.However, this solution is still not satisfactory. In order to make a premier account, we had to repeata lot of the same definitions as we had in the basic account class. That violates our fundamentalprinciple of laziness: never do twice what you could do once; instead, abstract and reuse.Inheritance lets us make a new class that’s like an old class, but with some parts overridden or newparts added. When defining a class, you can actually specify an argument, which is another class.You are saying that this new class should be exactly like the parent class or superclass, but withcertain definitions added or overridden. So, for example, we can sayclass Pre mie rAc cou nt ( Accou nt ):def cre ditL imit ( self ):return min ( self . cu rre ntB ala nce * 1.5 , 10000 000)6.01, Spring Semester, 2008—Course notes for Week 4 4class Eco nom yAc cou nt ( Accou nt ):def cre ditL imit ( self ):return min ( self . cu rre ntB ala nce *0.5 , 20.00)>>> a = Account (100)>>> b = Pre mie rAc cou nt (100)>>> c = Eco nom yAc cou nt (100)>>> a. creditL imit


View Full Document

MIT 6 01 - Study Guide

Documents in this Course
Week 1

Week 1

3 pages

Op-Amps

Op-Amps

8 pages

Op-Amps

Op-Amps

6 pages

Syllabus

Syllabus

14 pages

Planning

Planning

14 pages

Load more
Download Study Guide
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Study Guide and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Study Guide 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?