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)
→ booleanTrue if object is an instance of the
given type or any of the subclasses of
type.
issubclass(class, base)
→ booleanTrue 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( to
confirm that the argument value provided to this parameter is an
integer. An additional class, myParam,int)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 |
![]() | The |
![]() | The |
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.