Class Definition: the
We create a class definition with a
statement. We provide the class name, the parent classes, and the method
is the name of the class, and
this name is used to create new objects that are instances of the class.
Traditionally, class names are capitalized and class elements (variables
and methods) are not capitalized.
is the name of the parent
class, from which this class can inherit attributes and operations. For
simple classes, we define the parent as
Failing to list
object as a parent class is not —
strictly speaking — a problem; using
the superclass does make a few of the built-in functions a little easier
is a series of function
definitions, which define the class. All of these function definitions
must have a first positional argument,
Python uses to identify each object's unique attribute values.
can also contain assignment
statements which create instance variables and provide default
The suite typically begins with a comment string (often a
triple-quoted string) that provides basic documentation on the class.
This string becomes a special attribute, called
__doc__. It is available via the
"""Simulate a 6-sided die."""
def roll( self ):
def getValue( self ):
We imported the
random module to provide
the random number generator.
We defined the simple class named
claimed it as a subclass of
object. The indented
suite contains three elements.
The docstring, which provides a simple definition of the
real-world thing that this class represents. As with functions, the
docstring is retrieved with the
We defined a method function named
This method function has the mandatory positional parameter,
self, which is used to qualifty the instance
self variable is a namespace for
all of the attributes and methods of this object.
we defined a method function named
getValue. This function will return the
last value rolled.
roll method of a
Die object is executed, it sets that object's
self.value, to a random value.
Since the variable name,
value, is qualified by the
self, the variable is local to the
specific instance of the object. If we omitted the qualifier, Python
would look in the global namespace for a variable named