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.
A 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.).
Consider a class for defining and representing two-dimensional discreet points. First, the Java implementation
and now the corresponding Python implementation
The Python class definition is a compound statement which requires all member defintions to be indented to the same level from that of the class
keyword.
![]() | Note:
By default, all members or attributes of a Python class are public. Python provides a mechanism for defining private members, but we omit that discussion at this time and assume the user of a class will not directly modify a data field. |
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.
Objects are created for a user-defined class the same as for the built-in classes. The following example illustrates the use of the Python Point
class
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.
Objects are manipulated using methods defined by the corresponding class. A method contains declarations and executable statements to manipulate the given object.
A 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 self
reference as its first argument.
The reserved word self
within the method defintions is equivalent to this
in Java. A major difference, however, is Python requires you to use the self
reference while in Java it was hidden and only needed in special cases. Even though the self
reference is the first argument of the method definition, it is not used directly when a method is called. Consider the following method call for the pointA
object created above.
From the definition of the adjust()
method above, it appears that three actual arguments are required. But Python automatically passes the object reference to the method. A method invocation of the form
instance.method( args... )
is converted into a method call of the form
class.method( instance, args...)
The constructor of a Python class is defined using the special name __init__
. A class may only contain a single constructor. To provide multiple constructor options, you must use default values as was done in the Point
class example or use inheritance to create a new derived class with a new constructor.
![]() | Note:
While a class does not have to define a constructor, it is good practice to always provide one, especially if the class contains data fields. |
In Java, a class could contain the toString()
method which was used automatically when printing the value of an object or that object had to be converted to a string. Python defines the __str__()
method for the exact same thing. In the following example,
the __str__()
method is automatically called since we are trying to print the contents of the object. The same as would have been done in Java with the toString()
method. In Java, you could use the toString()
method directly
In Python, the __str__()
method can not be directly invoked. Instead, it is treated as an operator and can be used indirectly via the str()
constructor. In this example,
the __str__()
method is called by the str()
constructor to convert our point object to a string. If the __str__()
method is not defined for a class, Python uses the default action of printing the object type and its reference address.
![]() | Note:
Class methods of the form |
In 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 variables are specified by preceding the name with the self
reference. Even though a data field can be defined within any method, common practice dictates that data fields should be defined within the constructor. The Point
class defines two data fields in the constructor, xCoord
and yCoord
,
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 self
reference.
Any 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.
Python objects are typically composed of other objects. In the class defined above, a Point
object contains two numeric coordinate values. In object-oriented terminology, we call this a has-a relationship since a Point
has numeric values. Consider the following class definition
which defines a geometric line in the two-dimensional Cartesian coordinate system; a Line
line is composed of two Point
objects.
The 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.
In the next example, we define a class to represent a student record and provide serveral operations for obtaining information from that data.
The getClass()
method is a common implementation for the problem of selecting a descriptive name for a code representation. We could use a list and create a more compact form as shown below
We then use this class to create a second class to store a list of student objects. The Student List
class is also defined within the student.py module.