|
Defining ClassesText Files Table Of Contents Operator Overloading Page Contents (hide) Since Python is an object-oriented scripting language it must provide a means for you to define your own classes. Defining and using classes is much easier in Python than other languages such as C++ and Java. In addition to standard object-oriented concepts, Python also allows for multiple inheritance and operator overloading. In object-oriented languages, an object is an entity corresponding to an underlying objective. The object stores data for the given entity. A class represents a collection of related objects and is the blueprint which defines the construction of an object. Objects are instantiated or created from classes. The ClassA class is the blueprint which defines the construction of an object. A class definition contains
Objects are instantiated or created from classes. A class of objects is the collection of objects created from the same class (i.e. a collection of float objects.). Sample ClassConsider a class for defining and representing two-dimensional discreet points. First, the Java implementation Program: Point.java File: Point.java
// Point.java // Defines a class to represent two-dimensional discrete points. public class Point { private int xCoord; private int yCoord; public Point() { xCoord = yCoord = 0; } public Point( int x, int y ) { xCoord = x; yCoord = y; } public String toString() { return "(" + xCoord + ", " + yCoord + ")"; } public int getX() { return xCoord; } public int getY() { return yCoord; } public void shift( int xInc, int yInc ) { xCoord = xCoord + xInc; yCoord = yCoord + yInc; } } and now the corresponding Python implementation Program: point.py File: point.py
# point.py # Defines a class to represent two-dimensional discrete points. class Point : def __init__( self, x = 0, y = 0 ) : self.xCoord = x self.yCoord = y def __str__( self ) : return "(" + str( self.yCoord ) + ", " + str( self.yCoord ) + ")" def getX( self ) : return self.XCoord def getY( self ) : return self.yCoord def shift( self, xInc, yInc ) : self.xCoord += xInc self.yCoord += yInc The Python class definition is a compound statement which requires all member defintions to be indented to the same level from that of the
It has been mentioned several times that everything in Python is an object. We saw that not only are data types objects, but function definitions were also objects and function names are variables. The same is true for classes. A class definition creates an object with the various attributes (data fields and methods) and the class name is simply a variable referencing that object. Object InstantiationObjects are created for a user-defined class the same as for the built-in classes. The following example illustrates the use of the Python from point import * pointA = Point( 5, 7 ) pointB = Point() which results in two objects, each with its own instance variables If the class is defined in a separate module as is done here, then we must import it before it can be used. In Java, each class had to be defined within its own file which was named the same as the class. This is not the case in Python. Multiple classes can be defined within a single module and the module name is independent of any definition it may contain. MethodsObjects are manipulated using methods defined by the corresponding class. A method contains declarations and executable statements to manipulate the given object. Method DefinitionA method definition is similar in appearance to that of a function. There are two main differences, however. First, a method is defined as part of a class definition as indicated by its indentation in respect to the class header. Second, a class method must contain the The reserved word pointA.shift( 10, 15 ) From the definition of the instance.method( args... ) is converted into a method call of the form class.method( instance, args...) ConstructorThe constructor of a Python class is defined using the special name
Special String MethodIn Java, a class could contain the print "pointA: ", pointA print "pointB: ", pointB the // Java method call String myString = pointA.toString(); In Python, the myString = str( pointA ) the
Data FieldsIn Python, data fields like all other variables are not explicitly defined. Instead, any instance variable created within the constructor or a method becomes a data field. Instance VariablesInstance variables are specified by preceding the name with the def __init__( self, x = 0, y = 0 ) : self.xCoord = x self.yCoord = y while the two arguments, x and y, are simply local variables that can be used within the constructor. Just as in Java, data fields can be used within any method. But you must remember to precede the data field name with the Mutable ObjectsAny object that stores data is said to have a state. The object’s state is the current set of values that it contains. Objects are divided into two distinct categories: mutable and immutable An immutable object is one in which the state cannot be changed once it is created. If the data fields of the obect can be changed after the object is created, the object is said to be mutable. In Python only the list, dictionary, and file primitive types are mutable. Object CompositionPython objects are typically composed of other objects. In the class defined above, a Program: line.py File: line.py
# line.py # import math class Line : def __init__( self, fromPoint, toPoint ) : self.startPoint = fromPoint self.endPoint = toPoint def length( self ) : xDiff = self.startPoint.getX() - self.endPoint.getX() yDiff = self.startPoint.getY() - self.endPoint.getY() return math.sqrt( xDiff * xDiff + yDiff * yDiff ) def slope( self ) : if isVertical() : return None else : run = self.startPoint.getX() - self.endPoint.getX() rise = self.startPoint.getY() - self.endPoint.getY() return rise / float( run ) def isVertical( self ) : return self.startPoint.getX() == self.endPoint.getX() def isHorizontal( self ) : return self.startPoint.getY() == self.endPoint.getY() def shift( self, x, y ) : self.startPoint.shift( x, y ) self.endPoint.shift( x, y ) def getStartPoint( self ) : return self.startPoint def getEndPoint( self ) : return self.endPoint which defines a geometric line in the two-dimensional Cartesian coordinate system; a Class ExamplesThe following examples further illustrate the use of classes in Python. The first example creates a class to represent a die that can be tossed using the random number generator. from random import randint class Die : def __init__( self, numFaces ) : if numFaces < 4 : self.numFaces = 4 else : self.numFaces = numFaces self.faceValue = 1 def roll( self ) : self.faceValue = randint( 1, self.numFaces ) return self.faceValue def value( self ) : return self.faceValue def __str__( self ) : return "[%d ! %d]" % (self.faceValue, self.numFaces ) # The main routine. die1 = Die() die2 = Die( 12 ) print die1.roll() print die2.roll() In the next example, we define a class to represent a student record and provide serveral operations for obtaining information from that data. # student.py # # Defines a class to represent information for an individual student. def class Student : "Represents an individual student." def __init__( self, idNum = 0, classStanding = 0, firstName = "", lastName = "", gpa = 0.0 ) : self.idNum = idNum self.classStanding = classStanding self.firstName = firstName self.lastName = lastName self.gpa = gpa def getClass() : """Returns the string representation for the student's classification code.""" if self.classStanding == 0 : return "Freshman" elif self.classStanding == 1 : return "Sophomore" elif self.classStanding == 2 : return "Junior" else return "Senior" def getName( reversed ) : """Returns the student's name in one or two formats: 'first last' if reversed is false or 'last first' if reversed is true.""" if reversed == False : return self.firstName + " " + self.lastName else : return self.lastName + " " + self.firstName def getId() : return self.idNum def getGPA() : return self.gpa The def getClass( self ) : classList = [ "Freshman", "Sophomore", "Junior", "Senior" ] return classList[ self.classStanding ] We then use this class to create a second class to store a list of student objects. The def class StudentList : def __init__( self ) : self.theList = [] def addStudent( self, student ) : self.theList.add( student ) def deleteStudent( self, idNum ) : return None def findStudent( self, idNum ) : return None def findHighestGPA( self ) : return None def printReport( self ) : return None Static Members | |||||||
© 2006 - 2008: Rance Necaise - Page last
modified on September 30, 2006, at 07:03 PM
|