csci/cmpe 4341 topic: programming in python chapter 7: introduction to object- oriented programming...

38
CSCI/CMPE 4341 Topic: CSCI/CMPE 4341 Topic: Programming in Python Programming in Python Chapter 7: Introduction to Chapter 7: Introduction to Object-Oriented Object-Oriented Programming in Python Programming in Python Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 [email protected] 1

Upload: frank-poole

Post on 01-Jan-2016

235 views

Category:

Documents


1 download

TRANSCRIPT

  • CSCI/CMPE 4341 Topic: Programming in PythonChapter 7: Introduction to Object-Oriented Programming in PythonXiang LianThe University of Texas Pan AmericanEdinburg, TX [email protected] *

  • ObjectivesIn this chapter, you will:Become aware of reasons for using objects and classesCreate Python abstract data types (ADTs), classesUnderstand how to create, use and destroy objects of a classControl access to object attributes and methodsLearn the class inheritance in Python

    *

  • IntroductionWe humans are very good in recognizing and working with objects, such as a pen, a dog, or a human beingWe 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. *

  • 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. *

  • Introduction (cont'd)In addition to attributes, all objects exhibit behaviorsA dog eats, barks, wags its tail, plays, and begsA dog exhibits many more other behaviors than this short listAnother thing we need to remember about objects is that objects interact between each other*

  • ObjectsObjects are packages that contain data and functions (methods) that can be performed on the data*

  • Objects (cont'd)Data could be considered to be attributes and functions are considered to be behaviors of the objectWe can say that the attributes and behaviors are encapsulated into an object*

  • 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*

  • Object OrientationClassesEncapsulate dataAttributesEncapsulate functionsBehaviorsAct as blueprintsObjects are instantiated from classesImplement information hiding*

  • Object-Oriented ProgrammingUnit of object-oriented programming is the classUser-defined typesContain dataAttributesFunctional components that manipulate dataMethodsInvoked in response to messages sent to objectsClasses are focus of attention rather than functions (in procedural programming)Enable software reuseClasses may be derived from other classesClasses may contain objects of other classes

    *

  • Class DeclarationDefining a ClassClass headerKeyword class begins definitionFollowed by name of class and colon (:)Body of classIndented block of codeDocumentation stringDescribes the classOptionalAppears immediately after class header

    *

  • Class Declaration (cont'd)Defining a ClassConstructor method __init__Executes each time an object is createdInitialize attributes of classReturns NoneObject referenceAll methods must at least specify this one parameterRepresents object of class from which a method is calledCalled self by convention

    *

    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-23self.minute = 0 # 0-59self.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)

    *

    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 attributesprint ("The attributes of time1 are: ")print ("time1.hour:", time1.hour)print ("time1.minute:", time1.minute)print ("time1.second:", time1.second)

    # access object's methodsprint ("\nCalling method printMilitary:")time1.printMilitary() print ("\nCalling method printStandard:")time1.printStandard() # change value of object's attributesprint ("\n\nChanging time1's hour attribute...")time1.hour = 25print ("Calling method printMilitary after alteration:")time1.printMilitary()

    *

  • Special Attributes Introspection capabilitiesPythons ability to provide information about itselfSpecial attributesBelong to classes or objects of classesCreated by Python when class is defined or object is createdAll classes have attributes in commonProvide information about the class or object of a class to which they belongPreceded and followed by double underscores (__)*

  • *

    Attribute

    Description

    __bases__

    A tuple that contains base classes from which the class directly inherits. If the class does not inherit from other classes, the tuple is empty. [Note: We discuss base classes and inheritance in Chapter9, Object-Oriented Programming: Inheritance.]

    __dict__

    A dictionary that corresponds to the classs namespace. Each key-value pair represents an identifier and its value in the namespace.

    __doc__

    A classs docstring. If the class does not specify a docstring, the value is None.

    __module__

    A string that contains the module (file) name in which the class is defined.

    __name__

    A string that contains the classs name.

    Fig. 7.3Special attributes of a class.

    Attribute

    Description

    __class__

    A reference to the class from which the object was instantiated.

    __dict__

    A dictionary that corresponds to the objects namespace. Each key-value pair represents an identifier and its value in the namespace.

    Fig. 7.5Special attributes of an object of a class.

    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 win32Type "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

    Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "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

    Special attributes for classesSpecial attributes for objects*

  • Controlling Access to Attributes Controlling Access to AttributesClients may access a classs attributes directlyAllows clients to set inconsistent values for attributesPython allows class to prevent client from accessing data directlyAttribute naming conventions used to hide data*

  • Get and Set Methods Access methodsAllow data of class to be read and written in controlled mannerGet and Set methodsAllow clients to read and write the values of attributes respectively

    *

  • Get and Set Methods (cont'd)Control attributes hidden from direct access by clientBy convention, attributes not to be accessed directly are preceded with a single underscore (_)Get methodsControl format of data being received by clientSet methodsScrutinize attempts by client to change dataEnsures data is appropriate for specific attributesFor example, changing a date attribute to 37 would fail because no month has 37 daysReturn values indicating failed attempts to change data or display error messagesExceptions*

    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-23self._minute = 0 # 0-59self._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

  • Private Attributes Data and attributes not to be accessed by clients of a classPrivate attributes preceded with double underscore (__)Causes Python to perform name manglingChanges name of attribute to include information about the classFor example, attribute __hour in class Time becomes _Time__hour

    *

    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 memberself.__privateData = "private" # private data member

    Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "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

    *

  • ConstructorDefault constructorsDefault values provided for all argumentsConstructor may be invoked with no argumentsDefault argumentsSpecify initial values for object attributes Used if client does not specify an argument at construction timeKeyword argumentsClient may specify values for only certain, named arguments

    *

    2002 Prentice Hall. All rights reserved.Outline

    Time3.py1 # Fig: 7.13: Time3.py2 # 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

  • DestructorsDestructorsMethod is named __del__Executed when object is destroyedNo more references to object existPerforms termination housekeeping before Python reclaims object memoryTypically used to close network or database connections

    *

  • Class Attributes One copy of attribute shared by all objects of a classRepresents class-wide informationProperty of the class, not an object of the classInitialized once in a class definitionDefinition of class attribute appears in body of class definition, not a method definitionAccessed through the class or any object of the classMay exist even if no objects of class exist

    *

    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 = firstself.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 ))

    EmployeeWithClassAttribute.py*

    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 objectsemployee1 = Employee( "Susan", "Baker" )employee2 = Employee( "Robert", "Jones" )employee3 = employee1 print ("Number of employees after instantiation is", \employee1.count) # explicitly delete employee objects by removing referencesdel employee1del employee2del employee3 print ("Number of employees after deletion is", \Employee.count)

    Number of employees before instantiation is 0Employee constructor for Baker, SusanEmployee constructor for Jones, RobertNumber of employees after instantiation is 2Employee destructor for Jones, RobertEmployee destructor for Baker, SusanNumber of employees after deletion is 0

    *

  • Inheritance: Base Classes and Derived ClassesBase classCalled superclass in other programming languagesOther classes inherit its methods and attributesDerived classCalled subclass in other programming languagesInherits from a base classGenerally overrides some base class methods and adds features *

  • Examples of Inheritance Hierarchies*

    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 = xValueself.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 constructorself.radius = float( radiusValue ) def area( self ):"""Computes area of a Circle"""

    return math.pi * self.radius ** 2

    # main program # examine classes Point and Circleprint ("Point bases:", Point.__bases__)print ("Circle bases:", Circle.__bases__)

    *

    2002 Prentice Hall. All rights reserved.Outline

    fig09_04.py# demonstrate class relationships with built-in function issubclassprint ("\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 objectcircle = Circle( 120, 89, 2.7 ) # create Circle object # demonstrate object relationship with built-in function isinstanceprint ("\ncircle is a Point object:", isinstance( circle, Point ))print ("point is a Circle object:", isinstance( point, Circle )) # print Point and Circle objectsprint ("\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: 1Point is a subclass of Circle: 0circle is a Point object: 1point is a Circle object: 0point members: {'y': 50, 'x': 30}circle members: {'y': 89, 'x': 120, 'radius': 2.7000000000000002}Area of circle: 22.9022104447 *

  • *

    Some slides are borrowed and revised from lecture slides of the textbook***