10
7/23/2019 12-01-slides4up http://slidepdf.com/reader/full/12-01-slides4up 1/10 1 Michigan State University CSE 231 1 ! Today: Program Development with Classes  (Punch & Enbody, Chapter 13) ! Next: More on Files and Exceptions (Punch & Enbody, Chapter 14) Lecture Topics Michigan State University CS E 231 2 ! Exams scores now on D2L o Notify me of any inaccuracies ! Project # 9 o Scores sent via email ! Project #10 o Preliminary processing sent via email o Scores sent via email end of week?  Announcements Michigan State University CSE 231 3 ! Due Monday, Dec 6 th  ! Focuses on design, implementation, and testing of a Python class to create and manipulate times (UTC). ! Mostly the same methods as Project 10, but a few changes – follow the Project 11 specs! Computer Project #11 Michigan State University CS E 231 4 Three fundamental characteristics: !  Encapsulation ! Polymorphism ! Inheritance Object-Oriented Programming

12-01-slides4up

Embed Size (px)

Citation preview

Page 1: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 1/10

1

Michigan State University CSE 231 1

!  Today: Program Development with Classes

  (Punch & Enbody, Chapter 13)

!  Next: More on Files and Exceptions

(Punch & Enbody, Chapter 14)

Lecture Topics

Michigan State University CS E 231 2

!  Exams scores now on D2L

o  Notify me of any inaccuracies

!  Project # 9

o  Scores sent via email

!  Project #10

o  Preliminary processing sent via email

o  Scores sent via email end of week?

 Announcements

Michigan State University CSE 231 3

!  Due Monday, Dec 6th 

Focuses on design, implementation, andtesting of a Python class to create and

manipulate times (UTC).

!  Mostly the same methods as Project 10,

but a few changes – follow the Project 11

specs!

Computer Project #11

Michigan State University CS E 231 4

Three fundamental characteristics: 

!

 

Encapsulation

!  Polymorphism

!  Inheritance

Object-Oriented Programming

Page 2: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 2/10

2

Michigan State University CSE 231 5

Encapsulation

Provides modularity so the new data type can be reusedin other contexts, raise level of abstraction in client code

Hides implementation details of the new data type to

improve readability

o Leading underscore signifies a “hidden” attribute (should not beused directly by client code)

Provides an interface to manipulate objects of the new

data type

o The methods and data members whose names do not begin with

underscore(s)

o  All “overloaded” functions and operators

Michigan State University CS E 231 6

Polymorphism

!  The new data type allows use of standardoperations/functions, as appropriate

!  Examples:

construction

convert to string (for printing, display in shell)

o  operator overloading:

•  comparisons

• 

addition, subtraction, multiplication, division, etc.

o  len for new types of containers

Michigan State University CSE 231 7

Inheritance

!  Create new data type (class) by using an existing

class as the basis for the new class

The new class inherits all attributes of the existingclass

!  The new class can extend the existing class

o  add new data members and methods

redefine existing data members and methods

Michigan State University CS E 231 8

Example

 A company has built a set of classes to

display figures, such as circles, triangles

and rectangles.

 A programmer is given the task of creating a

class to display labeled  rectangles, which

are very similar to ordinary rectangles.

Page 3: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 3/10

3

Michigan State University CSE 231 9

 Alternative #1

!  The programmer starts from scratch and

creates an entirely new class to model

labeled rectangles.

!  Bad approach: wastes time and effort

because it doesn’t utilize existing rectangle

class.

Michigan State University CS E 231 10

!  Programmer copies source code for

rectangle class, modifies it to handle

labeled rectangles.

!  Bad approach: most of the code is the

same, and now there are two independent

copies of the source code (difficult to

maintain over time).

 Alternative #2

Michigan State University CSE 231 11

!  Programmer alters source code forexisting rectangle class to handle labeled

rectangles.

!  Bad approach: may break existingapplication programs (which depend onexisting class), may introduce errors intorectangle class (used to be error-free).

 Alternative #3

Michigan State University CS E 231 12

 Alternative #4

!  Use inheritance: labeled rectangle class

inherits all attributes of rectangle class,

extends it to handle new attributes.

!  Good approach: one copy of rectangle

class, no changes to rectangle class, allchanges isolated to labeled rectangle

class.

Page 4: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 4/10

4

Michigan State University CSE 231 13

Inheritance

!   A class can have a relationship with other

classes: inherits from

!  The “inherits from” relationships forms a

class hierarchy

Michigan State University CS E 231 14

Example:

Shape

Polygon

Rectangle

Square

CircleTriangle

Object

Michigan State University CSE 231 15

Classes related by a hierarchy

!  Every new class has a parent class o  shown in parenthesis in the class header

o  the class ‘above’ the new class in the class hierarchy

!   Any class can serve as the parent class for otherclasses, called its child classes.

!  In Python, the root class of the class hierarchy iscalled object 

Michigan State University CS E 231 16

class Shape (object):

...

class Circle (Shape):

...

class Polygon (Shape):

...

class Rectangle (Polygon):...

class Triangle (Polygon):...

class Square (Rectangle):

...  Square

Rectangle Triangle

object

Shape

PolygonCircle

Page 5: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 5/10

5

Michigan State University CSE 231 17

Sub-classes and super-classes

!  Each “descendant” of a class C is calleda sub-class of C:o 

C’s children

o  the children of C’s children

the children of the children of C’s children

o  ! 

!  Each “ancestor” of a class C is calleda super-class of C:o 

C’s parent

o  the parent of C’s parent

o  ! Michigan State University CS E 231 18

Square

Polygon

CircleRectangle Triangle

object

Shape

  s  u  p  e  r  -  c   l  a  s  s  s 

 u b - c l   a s  s 

The sub-class

relation isalso called

the “is a”

relation.

Michigan State University CSE 231 19

Inherited attributes

!  Child class inherits all data attr ibutes (instance

variables) and function attributes (methods) of its

parent class

!  Child class can introduce additional data

attributes and function attributes

!  Child class can redefine existing data attributes

and function attributes

Michigan State University CS E 231 20

 AttributesShape

Polygon

Rectangle

Square

CircleTriangle

tag __init__()

 __str__()

 __init__()area()

 __init__() __str__()

area()perimeter()

 __init__()

radius __init__()

 __str__()area()

perimeter()

sides __init__()

 __str__()perimeter()

Page 6: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 6/10

6

Michigan State University CSE 231 21

Namespace: collection of names and values

associated with those names (essentially a

dictionary)

Qualified name: name to the right of a “dot” (.)

signifying an attribute of an object

Scope Rules: determine the values associated

with names that can be legally referenced;

implement inheritance

Namespaces, Qualified names &

Scope Rules

Michigan State University CS E 231 22

Two naming styles

!  Unqualified

o  Variables: a = 10 + b

Functions: my_func( 50 ) 

!  Qualified, used to access attributes of

Modules: string.punctuation 

Classes: Date.__name[ self.__month ]

o  Class instances:

 A = Date(1, 1, 2014) A.get_iso()

Local: in current functionEnclosing: in outer functionGlobal: in global namespaceBuilt-in: in standard library

Michigan State University CSE 231 23

Scope rules for qualified names 

Use LCB (implements inheritance) 

!  Local: look inside the local object

the obj referenced by the expression to theleft of the ‘dot’ preceding the qualified name

!  Class: look inside the class definition

!  Base: look inside the base classes

(start at the parent and work up to rootobject)

Michigan State University CS E 231 24

Example: date.py

Python tutor visualization 

Page 7: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 7/10

7

Michigan State University CSE 231 25

Shape

Polygon

Rectangle

Square

CircleTriangle

tag __init__()

 __str__()

 __init__()area()

 __init__() __str__()

area()perimeter()

 __init__()

radius __init__()

 __str__()area()

perimeter()

sides __init__()

 __str__()perimeter()

Example: shapes.py

Michigan State University CS E 231 26

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

tag ‘shape’

Shape inst.:

class Shape( object ): 

def __init__( self, t="shape" ):"""create shape … """self.tag = t

. . .. . .

def main():

s = Shape(). . .

Main NS:

s

Michigan State University CSE 231 27

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

tag ‘shape’

Shape inst.:

class Shape( object ):

. . . 

def __str__( self ):"""return str … """return self.tag 

. . . 

def main():

. . . print( "s prints as", s )

Prints:

s prints as shape

Main NS:

s

Michigan State University CS E 231 28

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

class Shape( object ): 

def __init__( self, t="shape" ):"""create shape … ""”self.tag = t

. . .class Polygon( Shape ): 

def __init__(self, ss, t="polygon"):"""create polygon … """Shape.__init__( self, t )self.sides = [float(s) for s in ss]

. . .

def main():. . .

 p = Polygon([2,2,2,2,2])

tag ‘polygon’

sides [2.0,2.0,…]

Polygon inst.:

Main NS:

s ! 

P

Page 8: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 8/10

8

Michigan State University CSE 231 29

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

tag ‘polygon’

sides [2.0,2.0,…]

class Shape( object ): 

def __str__( self ):return self.tag

. . .class Polygon( Shape ): 

def __str__( self ):res = Shape.__str__( self ) + " [" + \", ".join([str(l) for l in \self.sides]) + "]”

return res. . .

def main():. . .

 print( "p prints as\n", p )

Prints: p prints as polygon [2.0, 2.0, 2.0,…]

Polygon inst.:

Main NS:

s ! 

P

Michigan State University CS E 231 30

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

tag ‘polygon’

sides [2.0,2.0,…]

Polygon inst.:

class Shape( object ): 

def __str__( self ):return self.tag

. . .class Polygon( Shape ): 

def perimeter( self ):return sum( self.sides )

. . .

def main():. . .

 print( "perim of p is", p.perimeter())

Prints: p prints as polygon [2.0, 2.0, …]

 perim of p is 10.0

Main NS:

s ! 

P

Michigan State University CSE 231 31

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

tag ‘triangle’

sides [2.0,2.0,3.0]

class Shape( object ): 

def __init__( self, t="shape" ):self.tag = t

. . .

class Polygon( Shape ): 

def __init__(self, ss, t="polygon"):Shape.__init__( self, t )self.sides = [float(s) for s in ss]

. . .

class Triangle( Polygon ): 

def __init__(self,s1=1,s2=1,s3=1, \t="triangle" ):

Polygon.__init__(self,[s1,s2,s3],t). . .

def main():. . .t = Triangle(2,2,3)

Main NS:

s ! 

P ! 

t

Triangle inst.:

Michigan State University CS E 231 32

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

class Shape( object ): 

def __str__( self ):return self.tag

. . .

class Polygon( Shape ): 

def __str__( self ):res = Shape.__str__( self ) + " [" + \", ".join([str(l) for l in \self.sides]) + "]”

return res. . .

class Triangle( Polygon ): 

. . .

def main():. . .

 print( "t prints as\n", t )

Prints:

t prints asTriangle [2.0, 2.0, 3.0]

tag ‘triangle’

sides [2.0,2.0,3.0]

Main NS:

s ! 

P ! 

t

Triangle inst.:

Page 9: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 9/10

9

Michigan State University CSE 231 33

Main NS:

s ! 

P ! 

t

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

class Shape( object ): 

def __str__( self ):return self.tag

. . .class Polygon( Shape ): 

def perimeter( self ):return sum( self.sides )

. . .

class Triangle( Polygon ): 

. . .

def main():. . .

 print( "perim of t is", t.perimeter() )

Prints:

t prints asTriangle [2.0, 2.0, 3.0]

tag ‘triangle’

sides [2.0,2.0,3.0]

 perim of t is 7.0

Triangle inst.:

Michigan State University CS E 231 34

Global NS:

Shape ! 

Polygon ! 

Triangle ! 

Rectangle ! 

Square ! 

Circle ! 

class Shape( object ): 

. . .

class Polygon( Shape ):. . .

class Triangle( Polygon ) :. . .

def area( self ):semip = sum( self.sides ) / 2.0

 prod = semip*(semip-self.sides[0])* \(semip-self.sides[1])* \(semip-self.sides[2])

return math.sqrt( prod ). . .

def main():. . .

 print( "area of t is", t.area() )

Prints:

t prints asTriangle [2.0, 2.0, 3.0]

tag ‘triangle’

sides [2.0,2.0,3.0]

Triangle inst.:

 perim of t is 7.0

area of t is 1.98

Main NS:

s ! 

P ! 

t

Michigan State University CSE 231 35

Global NS:

Shape

Polygon

Triangle

Rectangle

Square

Circle

tag ‘shape’

shape inst.:

tag ‘polygon’

sides [2.0,2.0, 2.0, 2.0, 2.0]

polygon inst.:

tag ‘triangle’

sides [2.0,2.0,3.0]

triangle inst.:

tag ‘rectangle’

sides [2.0,3.0]

rectange inst.:

Main NS:

s

P

t

r

Michigan State University CS E 231 36

Global NS:

Shape

Polygon

Triangle

Rectangle

Square

Circle

tag ‘shape’

shape inst.:

tag ‘polygon’

sides [2.0,2.0, 2.0, 2.0, 2.0]

polygon inst.:

tag ‘triangle’

sides [2.0,2.0,3.0]

triangle inst.:

tag ‘rectangle’

sides [2.0,3.0]

rectange inst.:

tag ‘square’

sides [5.0,5.0]

square inst.:

Main NS:

s

P

t

r

sq

Page 10: 12-01-slides4up

7/23/2019 12-01-slides4up

http://slidepdf.com/reader/full/12-01-slides4up 10/10

10

Michigan State University CSE 231 37

Global NS:

Shape

Polygon

Triangle

Rectangle

Square

Circle

tag ‘shape’

shape inst.:

tag ‘polygon’

sides [2.0,2.0, 2.0, 2.0, 2.0]

polygon inst.:

tag ‘triangle’

sides [2.0,2.0,3.0]

triangle inst.:

tag ‘rectangle’

sides [2.0,3.0]

rectange inst.:

tag ‘square’

sides [5.0,5.0]

square inst.:

tag ‘circle’

radius 1

circle inst.:

Main NS:

s

P

t

r

sq

c

Michigan State University CS E 231 38

Namespaces are maps

!  Every object has a namespace (dictionary)

!  The object’s namespace is bound to a

special variable __dict__

o  Collection of all local things (variables,

functions, etc.) in the object

o  Accessed by name (the key)

Michigan State University CSE 231 39

Dictionary for class Date

 __module__ __main__

 __weakref__ <attribute '__weakref__' of 'Date' objects>

 __dict__ <attribute '__dict__' of 'Date' objects>

 __doc__ None

 __init__ <function Date.__init__ at 0x02305108>

 __repr__ <function Date.__repr__ at 0x0228A780>

 __str__ <function Date.__str__ at 0x0228A738>

set_from_iso <function Date.set_from_iso at 0x0226FA98>

get_iso <function Date.get_iso at 0x0228AA08>

get_mdy <function Date.get_mdy at 0x02308AE0>

validate <function Date.validate at 0x0228A6F0>

mth_name ['Invalid', 'January', 'February',!, 'December']

Michigan State University CS E 231 40

Dictionary for instance A

month 1

day 1

year 2014

valid True

Dictionary for instance B

month 12

day 31

year 2014

valid True