There are two built in functions of some importance to object
oriented programming. These are used to determine the class of an
object, as well as the inheritance hierarchy among classes.
-
isinstance
(
object
,
type
)
→ boolean
-
True if
object
is an instance of the
given
type
or any of the subclasses of
type
.
-
issubclass
(
class
,
base
)
→ boolean
-
True if class
class
is a subclass of
class
base
. This question is usually moot,
because most programs are designed to provide the expected classes
of objects. There are some occasions for deep paranoia; when
working with untrusted software, your classes may need to be sure
that other programmers are following the rules. In Java and C++,
the compiler can check these situations. In Python, the compiler
doesn't check this, so we may want to include run-time
checks.
-
super
(
type
)
-
This will return the superclass of the given type.
All of the basic factory functions (str
,
int
, float
,
long
, complex
,
unicode
, tuple
,
list
, dict
,
set
) are effectively class names. You can,
therefore, use a test like
isinstance(
myParam
,int)
to
confirm that the argument value provided to this parameter is an
integer. An additional class, basestring
is the
parent class of both str
and
unicode
.
The following example uses the isinstance
function to validate the type of argument values. First, we'll define a
Roulette wheel class, Wheel
, and two subclasses,
Wheel1
with a single zero and
Wheel2
with zero and double zero.
Example 22.3. wheel.py
import random
class Wheel( object ):
def value( self ):
return NotImplemented
class Wheel1( Wheel ):
def value( self ):
spin= random.randrange(37)
return str(spin)
class Wheel2( Wheel ):
def __init__( self ):
self.values= ['00'] + map( str, range(37) )
def value( self ):
return random.randchoice( self.values )
|
The Wheel class defines the
interface for Roulette wheels. The actual class definition does
nothing except show what the expected method functions should
be. We could call this an abstract definition of a
Wheel .
|
|
The Wheel1 subclass uses a simple
algorithm for creating the spin of a wheel. The
value method chooses a number between 0 and
36. It returns a string representation of the number. This has
only a single zero.
|
|
The Wheel2 subclass creates an
instance variable, values , to contain all
possible results. This includes the 37 values from 0 to 36, plus
an additional '00' value. The value method
chooses one of these possible results.
|
The following function expects that its parameter,
w
, is one of the subclasses of
Wheel
.
def simulate( w ):
if not isinstance( w, Wheel ):
raise TypeError( "Must be a subclass of Wheel" )
for i in range(10):
print w.value()
In this case, the simulate function checks its argument,
w
to be sure that it is a subclass of
Wheel
. If not, the function raises the built in
TypeError
.