Download presentation
Presentation is loading. Please wait.
Published byFrank Poole Modified over 9 years ago
1
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 lianx@utpa.edu 1
2
Objectives In this chapter, you will: – Become aware of reasons for using objects and classes – Create Python abstract data types (ADTs), classes – Understand how to create, use and destroy objects of a class – Control access to object attributes and methods – Learn the class inheritance in Python 2
3
Introduction We humans are very good in recognizing and working with objects, such as a pen, a dog, or a human being We learned to categorize them in such a way that make sense to us. We may categorize them as animate object, inanimate objects, pets, friends, etc. 3
4
Introduction (cont'd) We sometimes classify objects based on their attributes, for example, green apples or red apples, fat or slim people, etc. If you think about it each object has many attributes. If I ask you list the attributes of an orange, you probably could list many things such as color, shape, weight, smell, etc. 4
5
Introduction (cont'd) In addition to attributes, all objects exhibit behaviors A dog eats, barks, wags its tail, plays, and begs – A dog exhibits many more other behaviors than this short list Another thing we need to remember about objects is that objects interact between each other 5
6
Objects Objects are packages that contain data and functions (methods) that can be performed on the data 6
7
Objects (cont'd) Data could be considered to be attributes and functions are considered to be behaviors of the object We can say that the attributes and behaviors are encapsulated into an object 7
8
Objects (cont'd) The objects interact between each other through their interfaces As an example a date object may have a set of data consisting of month, day and year, and methods consisting of assign date, display date, yesterday and tomorrow 8
9
Object Orientation Classes – Encapsulate data Attributes – Encapsulate functions Behaviors – Act as blueprints Objects are instantiated from classes – Implement information hiding 9
10
Object-Oriented Programming Unit of object-oriented programming is the class – User-defined types – Contain data Attributes – Functional components that manipulate data Methods Invoked in response to messages sent to objects – Classes are focus of attention rather than functions (in procedural programming) – Enable software reuse Classes may be derived from other classes Classes may contain objects of other classes 10
11
Class Declaration 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 11
12
Class Declaration (cont'd) 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 12
13
2002 Prentice Hall. All rights reserved. Outline Time1.py # Fig. 7.1: Time1.py # Simple definition of class Time. 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 def printMilitary( self ): """Prints object of class Time in military format""" print ("%.2d:%.2d:%.2d" % \ ( self.hour, self.minute, self.second )) def printStandard( self ): """Prints object of class Time in standard format""" standardTime = "" if self.hour == 0 or self.hour == 12: standardTime += "12:" else: standardTime += "%d:" % ( self.hour % 12 ) standardTime += "%.2d:%.2d" % ( self.minute, self.second ) if self.hour < 12: standardTime += " AM" else: standardTime += " PM" print (standardTime) Class headerOptional documentation string Constructor method Object reference passed to each method Variables initialized and entered in class’s namespace 13
14
2002 Prentice Hall. All rights reserved. Outline Fig07_02.py # Fig. 7.2: fig07_02.py # Creating and manipulating objects of class Time. from Time1 import Time # import class definition from file time1 = Time() # create object of class Time # access object's attributes print ("The attributes of time1 are: ") print ("time1.hour:", time1.hour) print ("time1.minute:", time1.minute) print ("time1.second:", time1.second) # access object's methods print ("\nCalling method printMilitary:") time1.printMilitary() print ("\nCalling method printStandard:") time1.printStandard() # change value of object's attributes print ("\n\nChanging time1's hour attribute...") time1.hour = 25 print ("Calling method printMilitary after alteration:") 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 14
15
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 (__) 15
16
16
17
2002 Prentice Hall. All rights reserved. Outline Interactive Session (Fig. 7.4) 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 Time1 import Time >>> print (Time.__bases__) (,) >>> 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 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 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 __dict__ contains all items in object’s namespace Special attributes for classes Special attributes for objects 17
18
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
19
Get and Set Methods Access methods – Allow data of class to be read and written in controlled manner – Get and Set methods Allow clients to read and write the values of attributes respectively 19
20
Get and Set Methods (cont'd) 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
21
2002 Prentice Hall. All rights reserved. Outline Time2.py # Fig: 7.7: Time2.py # Class Time with accessor methods. class Time: """Class Time with accessor methods""" def __init__( self ): """Time constructor initializes each data member to zero""" self._hour = 0 # 0-23 self._minute = 0 # 0-59 self._second = 0 # 0-59 def setTime( self, hour, minute, second ): """Set values of hour, minute, and second""" self.setHour( hour ) self.setMinute( minute ) self.setSecond( second ) def setHour( self, hour ): """Set hour value""" if 0 <= hour < 24: self._hour = hour else: raise (ValueError, "Invalid hour value: %d" % hour) def setMinute( self, minute ): """Set minute value""" 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 setHour checks that value is valid before changing the hour attribute An exception is raised if value is invalid 21
22
2002 Prentice Hall. All rights reserved. Outline Time2.py def setSecond( self, second ): """Set second value""" if 0 <= second < 60: self._second = second else: raise (ValueError,"Invalid second value: %d" % second) def getHour( self ): """Get hour value""" return self._hour def getMinute( self ): """Get minute value""" return self._minute def getSecond( self ): """Get second value""" return self._second def printMilitary( self ): """Prints Time object in military format""" print ("%.2d:%.2d:%.2d" % \ ( self._hour, self._minute, self._second )) def printStandard( self ): """Prints Time object in standard format""" standardTime = "" The get methods simply return the values 22
23
2002 Prentice Hall. All rights reserved. Outline Time2.py if self._hour == 0 or self._hour == 12: standardTime += "12:" else: standardTime += "%d:" % ( self._hour % 12 ) standardTime += "%.2d:%.2d" % ( self._minute, self._second ) if self._hour < 12: standardTime += " AM" else: standardTime += " PM" print (standardTime) 23
24
2002 Prentice Hall. All rights reserved. Outline Fig07_09.py # Fig. 7.9: fig07_09.py # Driver to test class TimeControl. from Time2 import Time time1 = Time() # print initial time print ("The initial military time is ", end="") time1.printMilitary() print ("\nThe initial standard time is ", end="") time1.printStandard() # change time time1.setTime( 13, 27, 6 ) print ("\n\nMilitary time after setTime is ", end="") time1.printMilitary() print ("\nStandard time after setTime is ", end ="") time1.printStandard() time1.setHour( 4 ) time1.setMinute( 3 ) time1.setSecond( 34 ) print ("\n\nMilitary time after setHour, setMinute, setSecond is ", end="") time1.printMilitary() print ("\nStandard time after setHour, setMinute, setSecond is ", end="") time1.printStandard() setTime used to change value of time Each set method used to change attributes individually 24
25
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 25
26
2002 Prentice Hall. All rights reserved. Outline Private.py Interactive Session (Fig. 7.12) # Fig. 7.11: Private.py # Class with private data members. class PrivateClass: """Class that contains public and private data""" def __init__( self ): """Private class, contains public and private data members""" self.publicData = "public" # public data member self.__privateData = "private" # private data member 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 Private import PrivateClass >>> private = PrivateClass() >>> print (private.publicData) public >>> print (private.__privateData) Traceback (most recent call last): File " ", line 1, in ? AttributeError: PrivateClass instance has no attribute '__privateData' >>> >>> print (private._PrivateClass__privateData) private >>> private._PrivateClass__privateData = "modified" >>> print (private._PrivateClass__privateData) 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 26
27
Constructor 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 27
28
2002 Prentice Hall. All rights reserved. Outline 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 19 def setHour( self, hour ): 20 """Set hour value""" 21 22 if 0 <= hour < 24: 23 self.__hour = hour 24 else: 25 raise (ValueError, "Invalid hour value: %d" % hour) 26 27 def setMinute( self, minute ): 28 """Set minute value""" 29 30 if 0 <= minute < 60: 31 self.__minute = minute 32 else: 33 raise (ValueError, "Invalid minute value: %d" % minute) 34 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 28
29
2002 Prentice Hall. All rights reserved. Outline 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 ) # 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 ) 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 29
30
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 30
31
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 31
32
2002 Prentice Hall. All rights reserved. Outline # Fig. 7.15: EmployeeWithClassAttribute.py # Class Employee with class attribute count. class Employee: """Represents an employee""" count = 0 # class attribute def __init__( self, first, last ): """Initializes firstName, lastName and increments count""" self.firstName = first self.lastName = last Employee.count += 1 # increment class attribute print ("Employee constructor for %s, %s" \ % ( self.lastName, self.firstName )) def __del__( self ): """Decrements count and prints message""" Employee.count -= 1 # decrement class attribute print ("Employee destructor for %s, %s" \ % ( self.lastName, self.firstName )) Class attribute count is defined in class body Constructor increments value of count when an object is created Destructor decrements value of count when an object is destroyed EmployeeWithClas sAttribute.py 32
33
2002 Prentice Hall. All rights reserved. Outline fig07_16.py # Fig. 7.16: fig07_16.py # Demonstrating class attribute access. from EmployeeWithClassAttribute import Employee print ("Number of employees before instantiation is", \ Employee.count) # create two Employee objects employee1 = Employee( "Susan", "Baker" ) employee2 = Employee( "Robert", "Jones" ) employee3 = employee1 print ("Number of employees after instantiation is", \ employee1.count) # explicitly delete employee objects by removing references del employee1 del employee2 del employee3 print ("Number of employees after deletion is", \ 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 employee3 is bound to an existing object. No new object is created and the constructor is not invoked del keyword implicitly deletes each object by removing references and causes the destructor to execute each time an object is destroyed 33
34
Inheritance: Base Classes and Derived Classes Base class – Called superclass in other programming languages – Other classes inherit its methods and attributes Derived class – Called subclass in other programming languages – Inherits from a base class – Generally overrides some base class methods and adds features 34
35
Examples of Inheritance Hierarchies CommunityMember Employee Student Faculty Staff (single inheritance) Administrator Teacher (single inheritance) Alumnus (single inheritance) AdministratorTeacher (multiple inheritance) 35
36
2002 Prentice Hall. All rights reserved. Outline fig09_04.py # Fig 9.4: fig09_04.py # Derived class inheriting from a base class. import math class Point: """Class that represents geometric point""" def __init__( self, xValue = 0, yValue = 0 ): """Point constructor takes x and y coordinates""" self.x = xValue self.y = yValue class Circle( Point ): """Class that represents a circle""" def __init__( self, x = 0, y = 0, radiusValue = 0.0 ): """Circle constructor takes x and y coordinates of center point and radius""" Point.__init__( self, x, y ) # call base-class constructor self.radius = float( radiusValue ) def area( self ): """Computes area of a Circle""" return math.pi * self.radius ** 2 # main program # examine classes Point and Circle print ("Point bases:", Point.__bases__) print ("Circle bases:", Circle.__bases__) Base class Point Derived class Circle inherits from base class Point Unbound method call to base-class constructorTuple containing a class’s base classes (if any)Derived class adds new attributeDerived class adds new method 36
37
2002 Prentice Hall. All rights reserved. Outline fig09_04.py # demonstrate class relationships with built-in function issubclass print ("\nCircle is a subclass of Point:", \ issubclass( Circle, Point )) print ("Point is a subclass of Circle:", issubclass( Point, Circle )) point = Point( 30, 50 ) # create Point object circle = Circle( 120, 89, 2.7 ) # create Circle object # demonstrate object relationship with built-in function isinstance print ("\ncircle is a Point object:", isinstance( circle, Point )) print ("point is a Circle object:", isinstance( point, Circle )) # print Point and Circle objects print ("\npoint members:\n\t", point.__dict__) print ("circle members:\n\t", circle.__dict__) print ("\nArea of circle:", circle.area()) Point bases: () Circle bases: (,) Circle is a subclass of Point: 1 Point is a subclass of Circle: 0 circle is a Point object: 1 point is a Circle object: 0 point members: {'y': 50, 'x': 30} circle members: {'y': 89, 'x': 120, 'radius': 2.7000000000000002} Area of circle: 22.9022104447 Return 1 if first argument is a subclass of second argumentReturn 1 if first argument is an object or an instance of second argument Contains an object’s attributes and their values as key-value pairs 37
38
38
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.