Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2002 Prentice Hall. All rights reserved. 1 Object Oriented Programming Revisited Object Orientation –Classes Encapsulate data –Attributes Encapsulate.

Similar presentations


Presentation on theme: " 2002 Prentice Hall. All rights reserved. 1 Object Oriented Programming Revisited Object Orientation –Classes Encapsulate data –Attributes Encapsulate."— Presentation transcript:

1  2002 Prentice Hall. All rights reserved. 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

2  2002 Prentice Hall. All rights reserved. 2 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

3  2002 Prentice Hall. All rights reserved. 3 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

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

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

6  2002 Prentice Hall. All rights reserved. 6 Program Output The attributes of time1 are: time1.hour: 0 time1.minute: 0 time1.second: 0 Calling method printMilitary: 00:00:00 Calling method printStandard: 12:00:00 AM Changing time1's hour attribute... Calling method printMilitary after alteration: 25:00:00

7  2002 Prentice Hall. All rights reserved. 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 NameError: global name 'hour' is not defined

8  2002 Prentice Hall. All rights reserved. 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, isFull() 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

9  2002 Prentice Hall. All rights reserved. 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 )

10  2002 Prentice Hall. All rights reserved. 10 Time2.py 1 # Fig: 7.7: Time2.py 2 # Class Time with accessor methods. 3 4 class Time: 5 """Class Time with accessor methods""" 6 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 setTime( self, hour, minute, second ): 15 """Set values of hour, minute, and second""" 16 17 self.setHour( hour ) 18 self.setMinute( minute ) 19 self.setSecond( second ) 20 21 def setHour( self, hour ): 22 """Set hour value""" 23 24 if 0 <= hour < 24: 25 self._hour = hour 26 else: 27 raise ValueError, "Invalid hour value: %d" % hour 28 29 def setMinute( self, minute ): 30 """Set minute value""" 31 32 if 0 <= minute < 60: 33 self._minute = minute 34 else: 35 raise ValueError, "Invalid minute value: %d" % minute Attributes not to be accessed directly are preceded with underscore setHour checks that value is valid before changing the hour attribute An exception with an error message is raised if value is invalid

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

12  2002 Prentice Hall. All rights reserved. 12 Fig07_09.py 1 # Fig. 7.9: fig07_09.py 2 # Driver to test class TimeControl. 3 4 from Time2 import Time 5 6 time1 = Time() 7 8 # print initial time 9 print "The initial military time is", 10 time1.printMilitary() 11 print "\nThe initial standard time is", 12 time1.printStandard() 13 14 # change time 15 time1.setTime( 13, 27, 6 ) 16 print "\n\nMilitary time after setTime is", 17 time1.printMilitary() 18 print "\nStandard time after setTime is", 19 time1.printStandard() 20 21 time1.setHour( 4 ) 22 time1.setMinute( 3 ) 23 time1.setSecond( 34 ) 24 print "\n\nMilitary time after setHour, setMinute, setSecond is", 25 time1.printMilitary() 26 print "\nStandard time after setHour, setMinute, setSecond is", 27 time1.printStandard() setTime used to change value of time Each set method used to change attributes individually

13  2002 Prentice Hall. All rights reserved. 13 Interactive Session (Fig. 7.10) Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from Time2 import Time >>> time1 = Time() >>> >>> time1.setHour( 30 ) Traceback (most recent call last): File " ", line 1, in ? File "Time2.py", line 27, in setHour raise ValueError, "Invalid hour value: %d" % hour ValueError: Invalid hour value: 30 >>> 30 is not a valid hour, therefore an error is generated

14  2002 Prentice Hall. All rights reserved. 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.E03/Programs_from_book/ch07/) 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.

15  2002 Prentice Hall. All rights reserved. 15 Solution Add this code to Figure 7.2: time2 = Time() time2.hour = 23 time2.minute = 8 time2.second = 23 print "\nNew time object: ", time2.printStandard() Modified Time1.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 printName( self ): print "Name:", self.name..

16  2002 Prentice Hall. All rights reserved. 16 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: 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 def __init__( self, h, m, s ): self._hour = h # 0-23 self._minute = m # 0-59 self._second = s # 0-59

17  2002 Prentice Hall. All rights reserved. 17 Time3.py 1 # Fig: 7.13: Time3.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.setTime( hour, minute, second ) 11 12 def setTime( self, hour, minute, second ): 13 """Set values of hour, minute, and second""" 14 15 self.setHour( hour ) 16 self.setMinute( minute ) 17 self.setSecond( second ) 18 [..] hour, minute and second are all defaulted to 0 if the client does not provide values Constructor uses setTime, which uses each attribute’s set method, ensuring data is valid

18  2002 Prentice Hall. All rights reserved. 18 fig07_14.py 1 # Fig. 7.14: fig07_14.py 2 # Demonstrating default constructor method for class Time. 3 4 from Time3 import Time 5 6 def printTimeValues( timeToPrint ): 7 timeToPrint.printMilitary() 8 print 9 timeToPrint.printStandard() 10 print 11 12 time1 = Time() # all default 13 time2 = Time( 2 ) # set hour; minute and second defaulted 14 time3 = Time( 21, 34 ) # set hour and minute; second defaulted 15 time4 = Time( 12, 25, 42 ) # all specified 16 17 print "Constructed with:" 18 19 print "\nall arguments defaulted:" 20 printTimeValues( time1 ) 21 22 print "\nhour specified; minute and second defaulted:" 23 printTimeValues( time2 ) 24 25 print "\nhour and minute specified; second defaulted:" 26 printTimeValues( time3 ) 27 28 print "\nhour, minute and second specified:" 29 printTimeValues( time4 ) Constructed with: all arguments defaulted: 00:00:00 12:00:00 AM hour specified; minute and second defaulted: 02:00:00 2:00:00 AM hour and minute specified; second defaulted: 21:34:00 9:34:00 PM hour, minute and second specified: 12:25:42 12:25:42 PM

19  2002 Prentice Hall. All rights reserved. 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

20  2002 Prentice Hall. All rights reserved. 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

21  2002 Prentice Hall. All rights reserved. 21 EmployeeWithClas sAttribute.py 1 # Fig. 7.15: EmployeeWithClassAttribute.py 2 # Class Employee with class attribute count. 3 4 class Employee: 5 """Represents an employee""" 6 7 count = 0 # class attribute 8 9 def __init__( self, first, last ): 10 """Initializes firstName, lastName and increments count""" 11 12 self.firstName = first 13 self.lastName = last 14 15 Employee.count += 1 # increment class attribute 16 17 print "Employee constructor for %s, %s" \ 18 % ( self.lastName, self.firstName ) 19 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.lastName, self.firstName ) Class attribute count is defined in class body, counts total number of employees Destructor decrements value of count when an object is destroyed Constructor increments value of count when an object is created

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

23  2002 Prentice Hall. All rights reserved. 23 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

24  2002 Prentice Hall. All rights reserved. 24 Date.py 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 daysPerMonth = [ 9 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] 10 11 def __init__( self, month, day, year ): 12 """Constructor for class Date""" 13 14 if 0 < month <= 12: # validate month 15 self.month = month 16 else: 17 raise ValueError, "Invalid value for month: %d" % month 18 19 if year >= 0: # validate year 20 self.year = year 21 else: 22 raise ValueError, "Invalid value for year: %y" % year 23 24 self.day = self.checkDay( 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() 34 Note difference between local and object variable Note again the self. prefix when referencing anything within this object

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

26  2002 Prentice Hall. All rights reserved. 26 EmployeeComposit ion.py 1 # Fig. 7.18: EmployeeComposition.py 2 # Definition of Employee class with composite members. 3 4 from Date import Date 5 6 class Employee: 7 """Employee class with Date attributes""" 8 9 def __init__( self, firstName, lastName, birthMonth, 10 birthDay, birthYear, hireMonth, hireDay, hireYear ): 11 """Constructor for class Employee""" 12 13 self.birthDate = Date( birthMonth, birthDay, birthYear ) 14 self.hireDate = Date( hireMonth, hireDay, hireYear ) 15 16 self.lastName = lastName 17 self.firstName = firstName 18 19 print "Employee constructor: %s, %s" \ 20 % ( self.lastName, self.firstName ) 21 22 def __del__( self ): 23 """Called before Employee destruction""" 24 25 print "Employee object about to be destroyed: %s, %s" \ 26 % ( self.lastName, self.firstName ) 27 28 def display( self ): 29 """Prints employee information""" 30 31 print "%s, %s" % ( self.lastName, self.firstName ) 32 print "Hired:", 33 self.hireDate.display() 34 print "Birth date:", 35 self.birthDate.display() Attributes birthDate and hireDate are Date objects

27  2002 Prentice Hall. All rights reserved. 27 fig07_19.py 1 # Fig. 7.19: fig07_19.py 2 # Demonstrating composition: an object with member objects. 3 4 from Date import Date 5 from EmployeeComposition import Employee 6 7 employee = Employee( "Bob", "Jones", 7, 24, 1949, 3, 12, 1988 ) 8 print 9 10 employee.display() 11 print Date constructor: 7/24/1949 Date constructor: 3/12/1988 Employee constructor: Jones, Bob 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 Employee constructor creates an Employee object and uses information in parameters to create Date objects specifying the employee’s date of hire and date of birth Note: the destructors are called when the program terminates (this line not needed, error in book)


Download ppt " 2002 Prentice Hall. All rights reserved. 1 Object Oriented Programming Revisited Object Orientation –Classes Encapsulate data –Attributes Encapsulate."

Similar presentations


Ads by Google