1 Object Oriented Programming Revisited Object Orientation Classes

  • Slides: 27
Download presentation
1 Object Oriented Programming Revisited • Object Orientation – Classes • Encapsulate data –

1 Object Oriented Programming Revisited • Object Orientation – Classes • Encapsulate data – Attributes • Encapsulate functions – Behaviors • Act as blueprints – Objects are instantiated from classes • Implement information hiding – Other objects know how to communicate, but not the class’s implementation details 2002 Prentice Hall. All rights reserved.

7. 2 Implementing a Time Abstract Data Type with a Class (II) • Defining

7. 2 Implementing a Time Abstract Data Type with a Class (II) • Defining a Class – Class header • Keyword class begins definition – Followed by name of class and colon (: ) – Body of class • Indented block of code – Documentation string • Describes the class • Optional • Appears immediately after class header 2002 Prentice Hall. All rights reserved. 2

7. 2 Implementing a Time Abstract Data Type with a Class (III) • Defining

7. 2 Implementing a Time Abstract Data Type with a Class (III) • Defining a Class – Constructor method __init__ • Executes each time an object is created • Initialize attributes of class • Returns None – Object reference • All methods must at least specify this one parameter • Represents object of class from which a method is called • Called self by convention 2002 Prentice Hall. All rights reserved. 3

1 # Fig. 7. 1: Time 1. py Optional 2 # Simple definition of

1 # Fig. 7. 1: Time 1. py Optional 2 # Simple definition of class Time. 3 documentation string 4 class Time: 5 """Time abstract data type (ADT) definition""" 6 Constructor 7 def __init__( self ): 8 """Initializes hour, minute and second to zero""" 9 10 self. hour = 0 # 0 -23 Object reference 11 self. minute = 0 # 0 -59 passed to each method 12 self. second = 0 # 0 -59 13 Variables initialized and 14 def print. Military( self ): 15 """Prints object of class Time in military format""" entered in class’s namespace 16 (no declarations, so this is 17 print "%. 2 d: %. 2 d" % were to define object’s 18 ( self. hour, self. minute, self. second ), 19 variables!)Time 1. py 20 def print. Standard( self ): 21 """Prints object of class Time in standard format""" 22 23 standard. Time = "" NB: remember the self. prefix for all 24 object variables, otherwise they would 25 if self. hour == 0 or self. hour == 12: 26 standard. Time += "12: " be local variables in each method! 27 else: 28 standard. Time += "%d: " % ( self. hour % 12 ) 29 30 standard. Time += "%. 2 d: %. 2 d" % ( self. minute, self. second ) 31 32 if self. hour < 12: 33 standard. Time += " AM" 34 else: 35 standard. Time += " PM" 2002 Prentice Hall. 36 print standard. Time, All rights reserved. 4

5 1 # Fig. 7. 2: fig 07_02. py Class name followed by ()

5 1 # Fig. 7. 2: fig 07_02. py Class name followed by () creates an object and 2 # Creating and manipulating objects of class Time. invokes the constructor 3 4 from Time 1 import Time # import class definition from file 5 6 time 1 = Time() # create object of class Time 7 Attributes of class accessed 8 # access object's attributes with object reference and 9 print "The attributes of time 1 are: " 10 print "time 1. hour: ", time 1. hour dot operator 11 print "time 1. minute: ", time 1. minute 12 print "time 1. second: ", time 1. second 13 14 # access object's methods 15 print "n. Calling method print. Military: ", 16 time 1. print. Military() Methods called with no 17 parameters because self is 18 print "n. Calling method print. Standard: ", Fig 07_02. py 19 time 1. print. Standard() passed by Python 20 21 # change value of object's attributes 22 print "nn. Changing time 1's hour attribute. . . " 23 time 1. hour = 25 24 print "Calling method print. Military after alteration: ", 25 time 1. print. Military() 2002 Prentice Hall. All rights reserved.

6 The attributes of time 1 are: time 1. hour: 0 time 1. minute:

6 The attributes of time 1 are: time 1. hour: 0 time 1. minute: 0 time 1. second: 0 Calling method print. Military: 00: 00 Calling method print. Standard: 12: 00 AM Changing time 1's hour attribute. . . Calling method print. Military after alteration: 25: 00 Program Output 2002 Prentice Hall. All rights reserved.

7 Forgetting the self. prefix in variables class Time: def __init__(self): hour = 7

7 Forgetting the self. prefix in variables class Time: def __init__(self): hour = 7 def display(self): print "here is the hour value: ", hour t = Time() t. display() here is the hour value: Traceback (most recent call last): File “self_error. py", line 14, in ? t. display() File “self_error. py", line 9, in display print "here is the hour value: ", hour Name. Error: global name 'hour' is not defined 2002 Prentice Hall. All rights reserved.

8 7. 4. 1 Get and Set Methods • Access methods – Allow data

8 7. 4. 1 Get and Set Methods • Access methods – Allow data of class to be read and written in controlled manner – Predicate methods • Read-only access methods that test the validity of a condition – For example, is. Full() for a container class determines if the container is full of objects – Get and Set methods • Allow clients to read and write the values of attributes respectively 2002 Prentice Hall. All rights reserved.

9 7. 4. 1 Get and Set Methods (II) • Access methods – Attributes

9 7. 4. 1 Get and Set Methods (II) • Access methods – Attributes hidden from direct access by client • By convention, attributes not to be accessed directly are preceded with a single underscore (_) – Get methods • Control format of data returned to client – Set methods • Scrutinize attempts by client to change data – Ensures data is appropriate for specific attributes • For example, changing a date attribute to 37 would fail because no month has 37 days – Return values indicating failed attempts to change data or display error messages • Exceptions (using keyword raise) 2002 Prentice Hall. All rights reserved.

10 1 # Fig: 7. 7: Time 2. py 2 # Class Time with

10 1 # Fig: 7. 7: Time 2. py 2 # Class Time with accessor methods. 3 Attributes not to be accessed 4 class Time: directly are preceded with 5 """Class Time with accessor methods""" 6 underscore 7 def __init__( self ): 8 """Time constructor initializes each data member to zero""" 9 10 self. _hour = 0 # 0 -23 11 self. _minute = 0 # 0 -59 12 self. _second = 0 # 0 -59 13 14 def set. Time( self, hour, minute, second ): 15 """Set values of hour, minute, and second""" 16 set. Hour checks that value 17 self. set. Hour( hour ) is valid before changing the 18 self. set. Minute( minute ) 19 self. set. Second( second ) hour attribute 20 An exception with an Time 2. py 21 def set. Hour( self, hour ): error message is raised 22 """Set hour value""" if value is invalid 23 24 if 0 <= hour < 24: 25 self. _hour = hour 26 else: 27 raise Value. Error, "Invalid hour value: %d" % hour 28 29 def set. Minute( self, minute ): 30 """Set minute value""" 31 32 if 0 <= minute < 60: 33 self. _minute = minute 34 else: 2002 Prentice Hall. 35 raise Value. Error, "Invalid minute value: %d" % minute All rights reserved.

11 36 37 def set. Second( self, second ): 38 """Set second value""" 39

11 36 37 def set. Second( self, second ): 38 """Set second value""" 39 40 if 0 <= second < 60: 41 self. _second = second 42 else: 43 raise Value. Error, "Invalid second value: %d" % second 44 45 def get. Hour( self ): 46 """Get hour value""" 47 The get methods simply 48 return self. _hour return the values 49 50 def get. Minute( self ): 51 """Get minute value""" 52 53 return self. _minute 54 55 def get. Second( self ): 56 """Get second value""" 57 58 return self. _second 59 60 def print. Military( self ): 61 """Prints Time object in military format""" 62 63 print "%. 2 d: %. 2 d" % 64 ( self. _hour, self. _minute, self. _second ), 65 66 def print. Standard( self ): 67 """Prints Time object in standard format""" 68 [rest is the same] Time 2. py 2002 Prentice Hall. All rights reserved.

12 1 # Fig. 7. 9: fig 07_09. py 2 # Driver to test

12 1 # Fig. 7. 9: fig 07_09. py 2 # Driver to test class Time. Control. 3 4 from Time 2 import Time 5 6 time 1 = Time() 7 8 # print initial time 9 print "The initial military time is" , 10 time 1. print. Military() set. Time used to 11 print "n. The initial standard time is" , change value of time 12 time 1. print. Standard() 13 14 # change time 15 time 1. set. Time( 13, 27, 6 ) 16 print "nn. Military time after set. Time is", 17 time 1. print. Military() 18 print "n. Standard time after set. Time is", 19 time 1. print. Standard() Each set method used to 20 21 time 1. set. Hour( 4 ) change attributes individually 22 time 1. set. Minute( 3 ) 23 time 1. set. Second( 34 ) 24 print "nn. Military time after set. Hour, set. Minute, set. Second is", 25 time 1. print. Military() 26 print "n. Standard time after set. Hour, set. Minute, set. Second is", 27 time 1. print. Standard() Fig 07_09. py 2002 Prentice Hall. All rights reserved.

13 Python 2. 2 b 2 (#26, Nov 16 2001, 11: 44: 11) [MSC

13 Python 2. 2 b 2 (#26, Nov 16 2001, 11: 44: 11) [MSC 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> from Time 2 import Time 30 is not a valid hour, >>> time 1 = Time() >>> therefore an error is >>> time 1. set. Hour( 30 ) generated Traceback (most recent call last): File "<stdin>", line 1, in ? File "Time 2. py", line 27, in set. Hour raise Value. Error, "Invalid hour value: %d" % hour Value. Error: Invalid hour value: 30 >>> Interactive Session (Fig. 7. 10) 2002 Prentice Hall. All rights reserved.

14 Intermezzo 1 www. daimi. au. dk/~chili/CSS/Intermezzi/24. 9. 1. html 1. Read & make

14 Intermezzo 1 www. daimi. au. dk/~chili/CSS/Intermezzi/24. 9. 1. html 1. Read & make sure you understand the programs in Figures 7. 1 and 7. 2, pages 228 and 230. Copy them to your own directory (from /users/chili/CSS. E 03/Programs_from_book/ch 07/) 2. Modify the program of Figure 7. 2 to create a second Time object. Set this object to represent the time 11. 08. 23 PM. 3. Modify the Time class of Figure 7. 1 and add a new object variable called name, initialized to your favorite football player. 4. Add a method that prints out the value of name. 2002 Prentice Hall. All rights reserved.

15 Solution Add this code to Figure 7. 2: time 2 = Time() time

15 Solution Add this code to Figure 7. 2: time 2 = Time() time 2. hour = 23 time 2. minute = 8 time 2. second = 23 print "n. New time object: ", time 2. print. Standard() Modified Time 1. py: class Time: """Time abstract data type (ADT) definition""" def __init__( self ): """Initializes hour, minute and second to zero""" self. hour = 0 # 0 -23 self. minute = 0 # 0 -59 self. second = 0 # 0 -59 self. name = “Zinedine Zidane" def print. Name( self ): print "Name: ", self. name . . 2002 Prentice Hall. All rights reserved.

7. 5 Using Default Arguments With Constructors • A default constructor explicitly sets all

7. 5 Using Default Arguments With Constructors • A default constructor explicitly sets all object attributes to default values (e. g. to 0) • A constructor can take arguments to set attributes: def __init__( self, h, m, s ): self. _hour = h # 0 -23 self. _minute = m # 0 -59 self. _second = s # 0 -59 • Default arguments – Specify initial values for object attributes in argument list – Used if client does not specify any arguments at construction time – Keyword arguments • Client may specify values for only certain, named arguments 2002 Prentice Hall. All rights reserved. 16

17 1 # Fig: 7. 13: Time 3. py 2 # Class Time with

17 1 # Fig: 7. 13: Time 3. py 2 # Class Time with default constructor. 3 4 class Time: 5 """Class Time with default constructor""" 6 7 def __init__( self, hour = 0, minute = 0, second = 0 ): 8 """Time constructor initializes each data member to zero""" 9 10 self. set. Time( hour, minute, second ) 11 12 def set. Time( self, hour, minute, second ): 13 """Set values of hour, minute, and second""" 14 hour, minute and second Constructor uses set. Time, 15 self. set. Hour( hour ) are all defaulted to 0 if the which uses each attribute’s set 16 self. set. Minute( minute ) 17 self. set. Second( second ) client does not provide values method, ensuring data is valid Time 3. py 18 [. . ] 2002 Prentice Hall. All rights reserved.

18 1 # Fig. 7. 14: fig 07_14. py 2 # Demonstrating default constructor

18 1 # Fig. 7. 14: fig 07_14. py 2 # Demonstrating default constructor method for class Time. 3 4 from Time 3 import Time 5 6 def print. Time. Values( time. To. Print ): 7 time. To. Print. print. Military () Constructed with: 8 print 9 time. To. Print. print. Standard () all arguments defaulted: 10 print 00: 00 11 12: 00 AM 12 time 1 = Time() # all default 13 time 2 = Time( 2 ) # set hour; minute and second defaulted hour specified; minute and second 14 time 3 = Time( 21, 34 ) # set hour and minute; second defaulted: 15 time 4 = Time( 12, 25, 42 ) # all specified 02: 00 16 2: 00 AM 17 print "Constructed with: " 18 hour and minute specified; second fig 07_14. py 19 print "nall arguments defaulted: " defaulted: 20 print. Time. Values( time 1 ) 21: 34: 00 21 9: 34: 00 PM 22 print "nhour specified; minute and second defaulted: " 23 print. Time. Values( time 2 ) hour, minute and second specified: 24 12: 25: 42 25 print "nhour and minute specified; second defaulted: " 12: 25: 42 PM 26 print. Time. Values( time 3 ) 27 28 print "nhour, minute and second specified: " 29 print. Time. Values( time 4 ) 2002 Prentice Hall. All rights reserved.

19 7. 6 Destructors • Constructor named __init__ • Destructor – Method is named

19 7. 6 Destructors • Constructor named __init__ • Destructor – Method is named __del__ – Executed when object is destroyed, i. e. when no more references to object exist – Can be used for housekeeping before Python reclaims object memory • Typically used to close network or database connections 2002 Prentice Hall. All rights reserved.

20 7. 7 Class Attributes • Class Attributes (like static variables in Java) –

20 7. 7 Class Attributes • Class Attributes (like static variables in Java) – One copy of attribute shared by all objects of a class – Represents “class-wide” information • Property of the class, not of an object of the class – Initialized once in the class definition (not in constructor) • Otherwise it would be re-initialized every time an object is created – Accessed through the class name or any object of the class • May exist even if no objects of class exist 2002 Prentice Hall. All rights reserved.

21 1 # Fig. 7. 15: Employee. With. Class. Attribute. py 2 # Class

21 1 # Fig. 7. 15: Employee. With. Class. Attribute. py 2 # Class Employee with class attribute count. Class attribute count is defined in class 3 body, counts total number of employees 4 class Employee: 5 """Represents an employee""" 6 7 count = 0 # class attribute 8 9 def __init__( self, first, last ): 10 """Initializes first. Name, last. Name and increments count""" 11 Constructor increments value of count when an 12 self. first. Name = first 13 self. last. Name = last object is created 14 15 Employee. count += 1 # increment class attribute 16 Destructor decrements value of count 17 print "Employee constructor for %s, %s" when an object is destroyed 18 % ( self. last. Name, self. first. Name ) Employee. With. Clas 19 s. Attribute. py 20 def __del__( self ): 21 """Decrements count and prints message""" 22 23 Employee. count -= 1 # decrement class attribute 24 25 print "Employee destructor for %s, %s" 26 % ( self. last. Name, self. first. Name ) 2002 Prentice Hall. All rights reserved.

22 1 # Fig. 7. 16: fig 07_16. py 2 # Demonstrating class attribute

22 1 # Fig. 7. 16: fig 07_16. py 2 # Demonstrating class attribute access. Employee objects are 3 created for employee 1 and 4 from Employee. With. Class. Attribute import Employee 5 employee 2 6 print "Number of employees before instantiation is" , 7 Employee. count 8 9 # create two Employee objects 10 employee 1 = Employee( "Susan", "Baker" ) 11 employee 2 = Employee( "Robert", "Jones" ) employee 3 is bound to an existing object. No new 12 employee 3 = employee 1 object is created and the constructor is not invoked 13 14 print "Number of employees after instantiation is" , 15 employee 1. count 16 17 # explicitly delete employee objects by removing references 18 del employee 1 del keyword removes a variable (here a reference to an object); the 19 del employee 2 20 del employee 3 destructor (__del__) doesn’t execute until all references to an 21 object have been removed. 22 print "Number of employees after deletion is" , 23 Employee. count Number of employees before instantiation is 0 Employee constructor for Baker, Susan Employee constructor for Jones, Robert Number of employees after instantiation is 2 Employee destructor for Jones, Robert Employee destructor for Baker, Susan Number of employees after deletion is 0 fig 07_16. py This object destroyed last since employee 3 pointed to it 2002 Prentice Hall. All rights reserved.

7. 8 Composition: Object References as Members of Classes • Composition – Defining a

7. 8 Composition: Object References as Members of Classes • Composition – Defining a class with objects of other classes • The attributes themselves are references to other objects 2002 Prentice Hall. All rights reserved. 23

24 1 # Fig. 7. 17: Date. py 2 # Definition of class Date.

24 1 # Fig. 7. 17: Date. py 2 # Definition of class Date. 3 4 class Date: 5 """Class that represents dates""" 6 7 # class attribute lists number of days in each month 8 days. Per. Month = [ 9 0, 31, 28, 31, 30, 31 ] 10 11 def __init__( self, month, day, year ): 12 """Constructor for class Date""" Note difference between local and object 13 14 if 0 < month <= 12: # validate month variable 15 self. month = month 16 else: 17 raise Value. Error, "Invalid value for month: %d" % month 18 Date. py 19 if year >= 0: # validate year 20 self. year = year 21 else: 22 raise Value. Error, "Invalid value for year: %y" % year 23 24 self. day = self. check. Day( day ) # validate day 25 26 print "Date constructor: ", 27 self. display() 28 29 def __del__( self ): 30 """Prints message when called""" 31 32 print "Date object about to be destroyed: " , 33 self. display() Note again the self. prefix when 34 2002 Prentice Hall. referencing anything within this object All rights reserved.

25 35 def display( self ): 36 """Prints Date information""" 37 38 print "%d/%d/%d"

25 35 def display( self ): 36 """Prints Date information""" 37 38 print "%d/%d/%d" % ( self. month, self. day, self. year ) 39 40 def check. Day( self, test. Day ): 41 """Validates day of the month""" 42 43 # validate day, test for leap year 44 if 0 < test. Day <= Date. days. Per. Month[ self. month ]: 45 return test. Day 46 elif self. month == 2 and test. Day == 29 and 47 ( self. year % 400 == 0 or 48 self. year % 100 != 0 and self. year % 4 == 0 ): 49 return test. Day 50 else: 51 raise Value. Error, "Invalid day: %d for month: %d" % 52 ( test. Day, self. month ) Note: if a < x < b: Date. py 2002 Prentice Hall. All rights reserved.

26 1 # Fig. 7. 18: Employee. Composition. py 2 # Definition of Employee

26 1 # Fig. 7. 18: Employee. Composition. py 2 # Definition of Employee class with composite members. 3 4 from Date import Date 5 Attributes birth. Date and 6 class Employee: hire. Date are Date objects 7 """Employee class with Date attributes""" 8 9 def __init__( self, first. Name, last. Name, birth. Month, 10 birth. Day, birth. Year, hire. Month, hire. Day, hire. Year ): 11 """Constructor for class Employee""" 12 13 self. birth. Date = Date( birth. Month, birth. Day, birth. Year ) 14 self. hire. Date = Date( hire. Month, hire. Day, hire. Year ) 15 16 self. last. Name = last. Name 17 self. first. Name = first. Name 18 19 print "Employee constructor: %s, %s" 20 % ( self. last. Name, self. first. Name ) 21 22 def __del__( self ): 23 """Called before Employee destruction""" 24 25 print "Employee object about to be destroyed: %s, %s" 26 % ( self. last. Name, self. first. Name ) 27 28 def display( self ): 29 """Prints employee information""" 30 31 print "%s, %s" % ( self. last. Name, self. first. Name ) 32 print "Hired: ", 33 self. hire. Date. display() 34 print "Birth date: ", 35 self. birth. Date. display() Employee. Composit ion. py 2002 Prentice Hall. All rights reserved.

27 1 # Fig. 7. 19: fig 07_19. py 2 # Demonstrating composition: an

27 1 # Fig. 7. 19: fig 07_19. py 2 # Demonstrating composition: an object with member objects. 3 (this line not needed, error in 4 from Date import Date 5 from Employee. Composition import Employee 6 7 employee = Employee( "Bob", "Jones", 7, 24, 1949, 3, 12, 1988 ) 8 print 9 10 employee. display() Employee constructor creates an 11 print book) Employee object and uses information in parameters to create Date objects specifying the employee’s date of hire and date of birth Date constructor: 7/24/1949 Date constructor: 3/12/1988 Employee constructor: Jones, Bob Hired: 3/12/1988 Birth date: 7/24/1949 Employee object about to be destroyed: Jones, Bob Date object about to be destroyed: 3/12/1988 Date object about to be destroyed: 7/24/1949 fig 07_19. py Note: the destructors are called when the program terminates 2002 Prentice Hall. All rights reserved.