Download presentation
Presentation is loading. Please wait.
1
Chapter 7 – Object-Based Programming
Outline Introduction Implementing a Time Abstract Data Type with a Class Special Attributes 7.4 Controlling Access to Attributes Get and Set Methods Private Attributes Using Default Arguments With Constructors Destructors Class Attributes Composition: Object References as Members of Classes 7.9 Data Abstraction and Information Hiding Software Reusability
2
7.1 Introduction 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 another class’s implementation details
3
Procedural Programming Languages
7.1 Introduction (II) Procedural Programming Languages Programming is action-oriented Unit of programming is the function Group of actions that performs some task Grouped together to form programs Data exists primarily in support of actions performed by functions
4
Object-Oriented Programming
7.1 Introduction (III) Object-Oriented Programming Unit of programming is the class User-defined types Contain data Attributes Functional components that manipulate data Methods Classes are focus of attention rather than functions
5
7.2 Implementing a Time Abstract Data Type with a Class
General Properties of Classes Methods Invoked in response to messages sent to objects Object interface Client-oriented Clients do not need to be familiar with implementation of class Enable software reuse Classes may be derived from other classes Classes may contain objects of other classes
6
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
7
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
8
Optional documentation string
1 # Fig. 7.1: Time1.py 2 # Simple definition of class Time. 3 4 class Time: """Time abstract data type (ADT) definition""" 6 def __init__( self ): """Initializes hour, minute and second to zero""" 9 self.hour = # 0-23 self.minute = 0 # 0-59 self.second = 0 # 0-59 13 def printMilitary( self ): """Prints object of class Time in military format""" 16 print "%.2d:%.2d:%.2d" % \ ( self.hour, self.minute, self.second ), 19 def printStandard( self ): """Prints object of class Time in standard format""" 22 standardTime = "" 24 if self.hour == 0 or self.hour == 12: standardTime += "12:" else: standardTime += "%d:" % ( self.hour % 12 ) 29 standardTime += "%.2d:%.2d" % ( self.minute, self.second ) 31 if self.hour < 12: standardTime += " AM" else: standardTime += " PM" Class header Optional documentation string Variables initialized and entered in class’s namespace Time1.py Object reference passed to each method Constructor method
9
36 print standardTime, Time1.py
10
Attributes of class accessed with object reference and dot operator
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 Fig07_02.py Attributes of class accessed with object reference and dot operator Methods called with no parameters because self is passed by Python
11
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 Program Output
12
Introspection capabilities
7.3 Special Attributes Introspection capabilities Python’s ability to provide information about itself Special attributes Belong to classes or objects of classes Created by Python when class is defined or object is created All classes have attributes in common Provide information about the class or object of a class to which they belong Preceded and followed by double underscores (__)
14
Interactive Session (Fig. 7.4)
Python 2.2b2 (#26, Nov , 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from Time1 import Time >>> print Time.__bases__ () >>> print Time.__dict__ {'printMilitary': <function printMilitary at 0x0079BF80>, '__module__': 'Time1', '__doc__': 'Time abstract data type (ADT) definition', '__init__': <function __init__ at 0x0077AB00>, 'printStandard': <function printStandard at 0x >} >>> print Time.__doc__ Time abstract data type (ADT) definition >>> print Time.__module__ Time1 >>> print Time.__name__ Time __bases__ special attribute outputs classes from which Time inherits __dict__ special attribute contains dictionary of items in class namespace Interactive Session (Fig. 7.4)
16
Interactive Session (Fig. 7.6)
Python 2.2b2 (#26, Nov , 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from Time1 import Time >>> time1 = Time() >>> print time1.__class__ Time1.Time >>> print time1.__dict__ {'second': 0, 'minute': 0, 'hour': 0} >>> print time1.__doc__ Time abstract data type (ADT) definition >>> print time1.__module__ Time1 __class__ has information about class from which object was instantiated Interactive Session (Fig. 7.6) __dict__ contains all items in object’s namespace
17
7.4 Controlling Access to Attributes
Clients may access a class’s attributes directly Allows clients to set inconsistent values for attributes Python allows class to prevent client from accessing data directly Attribute naming conventions used to hide data
18
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
19
7.4.1 Get and Set Methods (II)
Access methods Control 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 being received by 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
20
7.4.1 Get and Set Methods (III)
Exceptions may be returned when failed attempts are made Error messages Preferred technique for handling invalid attribute values Triggered with keyword raise followed by name of exception
21
Attributes not to be accessed directly are preceded with underscore
1 # Fig: 7.7: Time2.py 2 # Class Time with accessor methods. 3 4 class Time: """Class Time with accessor methods""" 6 def __init__( self ): """Time constructor initializes each data member to zero""" 9 self._hour = # 0-23 self._minute = 0 # 0-59 self._second = 0 # 0-59 13 def setTime( self, hour, minute, second ): """Set values of hour, minute, and second""" 16 self.setHour( hour ) self.setMinute( minute ) self.setSecond( second ) 20 def setHour( self, hour ): """Set hour value""" 23 if 0 <= hour < 24: self._hour = hour else: raise ValueError, "Invalid hour value: %d" % hour 28 def setMinute( self, minute ): """Set minute value""" 31 if 0 <= minute < 60: self._minute = minute else: raise ValueError, "Invalid minute value: %d" % minute Attributes not to be accessed directly are preceded with underscore Time2.py setHour checks that value is valid before changing the hour attribute An exception is raised if value is invalid
22
The get methods simply return the values
36 def setSecond( self, second ): """Set second value""" 39 if 0 <= second < 60: self._second = second else: raise ValueError, "Invalid second value: %d" % second 44 def getHour( self ): """Get hour value""" 47 return self._hour 49 def getMinute( self ): """Get minute value""" 52 return self._minute 54 def getSecond( self ): """Get second value""" 57 return self._second 59 def printMilitary( self ): """Prints Time object in military format""" 62 print "%.2d:%.2d:%.2d" % \ ( self._hour, self._minute, self._second ), 65 def printStandard( self ): """Prints Time object in standard format""" 68 standardTime = "" 70 Time2.py The get methods simply return the values
23
Time2.py 71 if self._hour == 0 or self._hour == 12:
standardTime += "12:" else: standardTime += "%d:" % ( self._hour % 12 ) 75 standardTime += "%.2d:%.2d" % ( self._minute, self._second ) 77 if self._hour < 12: standardTime += " AM" else: standardTime += " PM" 82 print standardTime, Time2.py
24
Interactive Session (Fig. 7.8)
Python 2.2b2 (#26, Nov , 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> raise ValueError, "This is an error message" Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: This is an error message Interactive Session (Fig. 7.8) Keyword raise triggers an exception ValueError is the name of the exception Description of error displayed when error occurs
25
setTime used to change value of time
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() Fig07_09.py setTime used to change value of time Each set method used to change attributes individually
26
Program Output The initial military time is 00:00:00
The initial military time is 00:00:00 The initial standard time is 12:00:00 AM Military time after setTime is 13:27:06 Standard time after setTime is 1:27:06 PM Military time after setHour, setMinute, setSecond is 04:03:34 Standard time after setHour, setMinute, setSecond is 4:03:34 AM Program Output
27
Interactive Session (Fig. 7.10)
Python 2.2b2 (#26, Nov , 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 "<stdin>", line 1, in ? File "Time2.py", line 27, in setHour raise ValueError, "Invalid hour value: %d" % hour ValueError: Invalid hour value: 30 >>> time1.setMinute( 99 ) File "Time2.py", line 35, in setMinute raise ValueError, "Invalid minute value: %d" % minute ValueError: Invalid minute value: 99 >>> time1.setSecond( -99 ) File "Time2.py", line 43, in setSecond raise ValueError, "Invalid second value: %d" % second ValueError: Invalid second value: -99 Attempt to change hour attribute to 30 is made Interactive Session (Fig. 7.10) 30 is not a valid hour, therefore an error is generated Attempt to change minute value to 99 fails and generates error Attempt to change second value to –99 fails and generates error
28
7.4.2 Private Attributes Private attributes
Data and attributes not to be accessed by clients of a class Private attributes preceded with double underscore (__) Causes Python to perform name mangling Changes name of attribute to include information about the class For example, attribute __hour in class Time becomes _Time__hour
29
Private.py Interactive Session (Fig. 7.12)
1 # Fig. 7.11: Private.py 2 # Class with private data members. 3 4 class PrivateClass: """Class that contains public and private data""" 6 def __init__( self ): """Private class, contains public and private data members""" 9 self.publicData = "public" # public data member self.__privateData = "private" # private data member Private.py Interactive Session (Fig. 7.12) Python 2.2b2 (#26, Nov , 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from Private import PrivateClass >>> private = PrivateClass() >>> print private.publicData public >>> print private.__privateData Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: PrivateClass instance has no attribute '__privateData' >>> print private._PrivateClass__privateData private >>> private._PrivateClass__privateData = "modified" modified Attempting to access attribute with double underscore causes an error Data can still be accessed because we know what the attribute is renamed to
30
7.5 Using Default Arguments With Constructors
Default constructors Default values provided for all arguments Constructor may be invoked with no arguments Default arguments Specify initial values for object attributes Used if client does not specify an argument at construction time Keyword arguments Client may specify values for only certain, named arguments
31
1 # Fig: 7.13: Time3.py 2 # Class Time with default constructor. 3 4 class Time: """Class Time with default constructor""" 6 def __init__( self, hour = 0, minute = 0, second = 0 ): """Time constructor initializes each data member to zero""" 9 self.setTime( hour, minute, second ) 11 def setTime( self, hour, minute, second ): """Set values of hour, minute, and second""" 14 self.setHour( hour ) self.setMinute( minute ) self.setSecond( second ) 18 def setHour( self, hour ): """Set hour value""" 21 if 0 <= hour < 24: self.__hour = hour else: raise ValueError, "Invalid hour value: %d" % hour 26 def setMinute( self, minute ): """Set minute value""" 29 if 0 <= minute < 60: self.__minute = minute else: raise ValueError, "Invalid minute value: %d" % minute 34 Time3.py 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
32
Time3.py 35 def setSecond( self, second ): 36 """Set second value"""
37 if 0 <= second < 60: self.__second = second else: raise ValueError, "Invalid second value: %d" % second 42 def getHour( self ): """Get hour value""" 45 return self.__hour 47 def getMinute( self ): """Get minute value""" 50 return self.__minute 52 def getSecond( self ): """Get second value""" 55 return self.__second 57 def printMilitary( self ): """Prints Time object in military format""" 60 print "%.2d:%.2d:%.2d" % \ ( self.__hour, self.__minute, self.__second ), 63 def printStandard( self ): """Prints Time object in standard format""" 66 standardTime = "" 68 Time3.py
33
Time3.py 69 if self.__hour == 0 or self.__hour == 12:
standardTime += "12:" else: standardTime += "%d:" % ( self.__hour % 12 ) 73 standardTime += "%.2d:%.2d" % ( self.__minute, self.__second ) 75 if self.__hour < 12: standardTime += " AM" else: standardTime += " PM" 80 print standardTime, Time3.py
34
Values specified for hour and minute, while second has default value
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 ): timeToPrint.printMilitary() print timeToPrint.printStandard() print 11 12 time1 = Time() # all default 13 time2 = Time( 2 ) # minute, second default 14 time3 = Time( 21, 34 ) # second default 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 ) fig07_14.py No values are specified, therefore hour, minute and second are initialized with default values of 0 Value specified for hour, while minute and second are initialized to default values Values specified for hour and minute, while second has default value Values specified for hour, minute and second
35
Program Output Constructed with: all arguments defaulted: 00:00:00
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 Program Output
36
7.6 Destructors Destructors Method is named __del__
Executed when object is destroyed No more references to object exist Performs termination housekeeping before Python reclaims object memory Typically used to close network or database connections
37
7.7 Class Attributes Class Attributes
One copy of attribute shared by all objects of a class Represents “class-wide” information Property of the class, not an object of the class Initialized once in a class definition Definition of class attribute appears in body of class definition, not a method definition Accessed through the class or any object of the class May exist even if no objects of class exist
38
Class attribute count is defined in class body
1 # Fig. 7.15: EmployeeWithClassAttribute.py 2 # Class Employee with class attribute count. 3 4 class Employee: """Represents an employee""" 6 count = # class attribute 8 def __init__( self, first, last ): """Initializes firstName, lastName and increments count""" 11 self.firstName = first self.lastName = last 14 Employee.count += 1 # increment class attribute 16 print "Employee constructor for %s, %s" \ % ( self.lastName, self.firstName ) 19 def __del__( self ): """Decrements count and prints message""" 22 Employee.count -= 1 # decrement class attribute 24 print "Employee destructor for %s, %s" \ % ( self.lastName, self.firstName ) Class attribute count is defined in class body EmployeeWithClassAttribute.py Constructor increments value of count when an object is created Destructor decrements value of count when an object is destroyed
39
Employee objects are created for employee1 and employee2
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", \ 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", \ 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", \ Employee.count Employee objects are created for employee1 and employee2 employee3 is bound to an existing object. No new object is created and the constructor is not invoked fig07_16.py del keyword implicitly deletes each object by removing references and causes the destructor to execute each time an object is destroyed 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
40
7.8 Composition: Object References as Members of Classes
Defining a class with objects of other classes The attributes themselves are references to other objects
41
Date.py 1 # Fig. 7.17: Date.py 2 # Definition of class Date. 3
"""Class that represents dates""" 6 # class attribute lists number of days in each month daysPerMonth = [ , 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] 10 def __init__( self, month, day, year ): """Constructor for class Date""" 13 if 0 < month <= 12: # validate month self.month = month else: raise ValueError, "Invalid value for month: %d" % month 18 if year >= 0: # validate year self.year = year else: raise ValueError, "Invalid value for year: %y" % year 23 self.day = self.checkDay( day ) # validate day 25 print "Date constructor:", self.display() 28 def __del__( self ): """Prints message when called""" 31 print "Date object about to be destroyed:", self.display() 34 Date.py
42
Date.py 35 def display( self ): 36 """Prints Date information""" 37
print "%d/%d/%d" % ( self.month, self.day, self.year ) 39 def checkDay( self, testDay ): """Validates day of the month""" 42 # validate day, test for leap year if 0 < testDay <= Date.daysPerMonth[ self.month ]: return testDay elif self.month == 2 and testDay == 29 and \ ( self.year % 400 == 0 or self.year % 100 != 0 and self.year % 4 == 0 ): return testDay else: raise ValueError, "Invalid day: %d for month: %d" % \ ( testDay, self.month ) Date.py
43
Class Date is imported so class Employee may define Date objects
1 # Fig. 7.18: EmployeeComposition.py 2 # Definition of Employee class with composite members. 3 4 from Date import Date 5 6 class Employee: """Employee class with Date attributes""" 8 def __init__( self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear ): """Constructor for class Employee""" 12 self.birthDate = Date( birthMonth, birthDay, birthYear ) self.hireDate = Date( hireMonth, hireDay, hireYear ) 15 self.lastName = lastName self.firstName = firstName 18 print "Employee constructor: %s, %s" \ % ( self.lastName, self.firstName ) 21 def __del__( self ): """Called before Employee destruction""" 24 print "Employee object about to be destroyed: %s, %s" \ % ( self.lastName, self.firstName ) 27 def display( self ): """Prints employee information""" 30 print "%s, %s" % ( self.lastName, self.firstName ) print "Hired:", self.hireDate.display() print "Birth date:", self.birthDate.display() Class Date is imported so class Employee may define Date objects EmployeeComposition.py Attributes birthDate and hireDate are Date objects
44
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 fig07_19.py 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 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
45
7.9 Data Abstraction and Information Hiding
Classes hide implementation details from their clients Data Abstraction Object-oriented languages create data types and express interactions between objects of data types Objects know what capabilities a structure offers, but not how the structure is implemented Abstract Data Types Provide formalizations of data to improve development process Representations of real world notions
46
7.9 Data Abstraction and Information Hiding (II)
Abstract Data Types (ADTs) Have a data representation Define operations performed on the data Example ADTs Stack Analogous to a pile of dishes Dishes are added and removed from top of a stack Last-in, first-out data structure Last item inserted (pushed) is always the first item removed (popped) Easily implemented with lists Python provides methods that allows lists to act like stacks
47
7.9 Data Abstraction and Information Hiding (III)
Example ADTs Queue Similar to a “waiting line” First-in, first-out order First item inserted (enqueued) is the first item removed (dequeued)
48
Python standard library
7.10 Software Reusability Python standard library Contains hundreds of predefined classes Well-defined, tested and documented Promote Rapid Application Development Programmers build applications using predefined classes Improve program debugging and maintenance
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.