Class Definition: the
class
Statement
We create a class definition with a
class
statement. We provide the class name, the parent classes, and the method
function definitions.
class
name
(parent)
:
suite
The
name
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.
The
parent
is the name of the parent
class, from which this class can inherit attributes and operations. For
simple classes, we define the parent as object
.
Failing to list object
as a parent class is not —
strictly speaking — a problem; using object
as
the superclass does make a few of the built-in functions a little easier
to use.
The
suite
is a series of function
definitions, which define the class. All of these function definitions
must have a first positional argument, self
, which
Python uses to identify each object's unique attribute values.
The
suite
can also contain assignment
statements which create instance variables and provide default
values.
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
help
function.
For example:
>>>
import random
>>>
class Die(object):
"""Simulate a 6-sided die."""
def roll( self ):
self.value= random.randrange(1,7)
return self.value
def getValue( self ):
return self.value
We imported the random
module to provide
the random number generator.
We defined the simple class named Die
, and
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 help
function.
-
We defined a method function named roll
.
This method function has the mandatory positional parameter,
self
, which is used to qualifty the instance
variables. The 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.
When the roll
method of a
Die
object is executed, it sets that object's
instance variable, self.value
, to a random value.
Since the variable name, value
, is qualified by the
instance variable, 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
value
.