using classes effectively
play

Using Classes Effectively [Andersen, Gries, Lee, Marschner, Van - PowerPoint PPT Presentation

CS 1110: Introduction to Computing Using Python Lecture 18 Using Classes Effectively [Andersen, Gries, Lee, Marschner, Van Loan, White] Announcements A3 due tonight at 11:59pm. Spring break next week: No office hours No


  1. CS 1110: Introduction to Computing Using Python Lecture 18 Using Classes Effectively [Andersen, Gries, Lee, Marschner, Van Loan, White]

  2. Announcements • A3 due tonight at 11:59pm. • Spring break next week:  No office hours  No consulting hours  Limited piazza 3/30/17 Using Classes Effectively 2

  3. Making Arguments Optional class Point3(object): • We can assign default values to """Instances are points in 3d space __init__ arguments x: x coord [float]  Write as assignments to y: y coord [float] parameters in definition z: z coord [float] """  Parameters with default values are optional def __init__(self,x=0,y=0,z=0): • Examples : """Initializer: makes a new Point  p = Point3() # (0,0,0) Precondition: x,y,z are numbers"""  p = Point3(1,2,3) # (1,2,3) self.x = x  p = Point3(1,2) # (1,2,0) self.y = y self.z = z  p = Point3(y=3) # (0,3,0) …  p = Point3(1,z=2) # (1,0,2) 3/30/17 Using Classes Effectively 3

  4. Making Arguments Optional class Point3(object): • We can assign default values to """Instances are points in 3d space __init__ arguments x: x coord [float]  Write as assignments to y: y coord [float] parameters in definition z: z coord [float] """  Parameters with default values are optional def __init__(self,x=0,y=0,z=0): • Examples : """Initializer: makes a new Point  p = Point3() # (0,0,0) Precondition: x,y,z are numbers""" Assigns in order  p = Point3(1,2,3) # (1,2,3) self.x = x  p = Point3(1,2) # (1,2,0) self.y = y Use parameter name when out of order self.z = z  p = Point3(y=3) # (0,3,0) …  p = Point3(1,z=2) # (1,0,2) Can mix two approaches 3/30/17 Using Classes Effectively 4

  5. Making Arguments Optional class Point3(object): • We can assign default values to """Instances are points in 3d space __init__ arguments x: x coord [float]  Write as assignments to y: y coord [float] parameters in definition z: z coord [float] """  Parameters with default values are optional def __init__(self,x=0,y=0,z=0): • Examples : """Initializer: makes a new Point  p = Point3() # (0,0,0) Precondition: x,y,z are numbers""" Assigns in order  p = Point3(1,2,3) # (1,2,3) self.x = x  p = Point3(1,2) # (1,2,0) self.y = y Use parameter name when out of order self.z = z  p = Point3(y=3) # (0,3,0) …  p = Point3(1,z=2) # (1,0,2) Can mix two approaches 3/30/17 Using Classes Effectively 5

  6. On Tuesday, we learned how to make: • Class definitions • Class specifications • Class variables • Methods • Attributes (using self ) • A constructor with __init__ 3/30/17 Using Classes Effectively 6

  7. Today • Class definitions • Class specifications • Class variables • Methods • Attributes (using self ) • A constructor with __init__ 3/30/17 Using Classes Effectively 7

  8. Designing Types • Type : set of values and the operations on them  int: ( set : integers; ops : +, –, *, /, …)  Time ( set : times of day; ops : time span, before/after, …)  Rectangle ( set : all axis-aligned rectangles in 2D; ops : contains, intersect, …) • To define a class, think of a real type you want to make 3/30/17 Using Classes Effectively 8

  9. Making a Class into a Type 1. Think about what values you want in the set  What are the attributes? What values can they have? 2. Think about what operations you want  This often influences the previous question • To make (1) precise: write a class invariant  Statement we promise to keep true after every method call • To make (2) precise: write method specifications  Statement of what method does/what it expects (preconditions) • Write your code to make these statements true! 3/30/17 Using Classes Effectively 9

  10. Planning out a Class: Time • What attributes ? • What invariants ? • What methods ? • What constructor ? (24-hour clock) 3/30/17 Using Classes Effectively 10

  11. Planning out a Class class Time(object): Class Invariant """Instances represent times of day. Instance Attributes: States what attributes are present hour: hour of day [int in 0..23] and what values they can have. min: minute of hour [int in 0..59]""" A statement that will always be true of any Time instance. def __init__(self, hour, min): """The time hour:min. Pre: hour in 0..23; min in 0..59""" def increment(self, hours, mins): Method Specification """Move this time <hours> hours States what the method does. and <mins> minutes into the future. Gives preconditions stating what Pre: hours is int >= 0; mins in 0..59""" is assumed true of the arguments. def isPM(self): """Returns: this time is noon or later.""" 3/30/17 Using Classes Effectively 11

  12. Implementing a Class • All that remains is to fill in the methods. (All?!) • When implementing methods: 1. Assume preconditions are true 2. Assume class invariant is true to start 3. Ensure method specification is fulfilled 4. Ensure class invariant is true when done • Later, when using the class:  When calling methods, ensure preconditions are true  If attributes are altered, ensure class invariant is true 3/30/17 Using Classes Effectively 14

  13. Implementing an Initializer def __init__(self, hour, min): """The time hour:min. Pre: hour in 0..23; min in 0..59""" This is true to start You put code here Instance variables: This should be true hour: hour of day [int in 0..23] at the end min: minute of hour [int in 0..59] 3/30/17 Using Classes Effectively 15

  14. Implementing an Initializer def __init__(self, hour, min): """The time hour:min. Pre: hour in 0..23; min in 0..59""" This is true to start A: B: C: Time.hour = hour hour = hour self.hour = hour Time.min = min min = min self.min = min Instance variables: D: hour: hour of day [int in 0..23] self.hour = Time.hour min: minute of hour [int in 0..59] self.min = Time.min This should be true at the end 3/30/17 Using Classes Effectively 16

  15. Implementing a Method Instance variables: hour: hour of day [int in 0..23] This is true to start min: minute of hour [int in 0..59] What we are supposed def increment(self, hours, mins): to accomplish """Move this time <hours> hours and <mins> minutes into the future. This is also true to start Pre: hours [int] >= 0; mins in 0..59""" ? self.min = self.min + mins self.hour = self.hour + hours You put code here Instance variables: hour: hour of day [int in 0..23] This should be true min: minute of hour [int in 0..59] at the end 3/30/17 Using Classes Effectively 17

  16. Implementing a Method Instance variables: hour: hour of day [int in 0..23] This is true to start min: minute of hour [int in 0..59] What we are supposed def increment(self, hours, mins): to accomplish """Move this time <hours> hours and <mins> minutes into the future. This is also true to start Pre: hours [int] >= 0; mins in 0..59""" self.min = self.min + mins You put code here self.hour = (self.hour + hours + self.min / 60) self.min = self.min % 60 self.hour = self.hour % 24 Instance variables: hour: hour of day [int in 0..23] This should be true min: minute of hour [int in 0..59] at the end 3/30/17 Using Classes Effectively 18

  17. Example: class Time 3/30/17 Using Classes Effectively 19

  18. Special Methods in Python class Point3(object): • __init__ for initializer """Instances are points in 3D space""" • __str__ for str() … • __repr__ for backquotes def __init__(self,x=0,y=0,z=0): • Start/end with 2 underscores """Initializer: makes new Point3""" …  This is standard in Python  Used in all special methods def __str__(self,q):  Also for special attributes """Returns: string with contents""" … • For a complete list, see def __repr__(self,q): http://docs.python.org/refere """Returns: unambiguous string""" nce/datamodel.html … 3/30/17 Using Classes Effectively 20

  19. Example: Converting Values to Strings str() Function Backquotes • Usage : str( <expression> ) • Usage : ` <expression> `  Evaluates the expression  Evaluates the expression  Converts it into a string  Converts it into a string • How does it convert? • How does it convert?  str(2) → '2'  `2` → '2'  str(True) → 'True'  `True` → 'True'  str('True') → 'True'  `'True'` → "'True'"  str(Point3()) →  `Point3()` → '(0.0,0.0,0.0)' "<class 'Point3'> (0.0,0.0,0.0)" 3/30/17 Using Classes Effectively 21

Recommend


More recommend