Python has two built-in decorators.
staticmethod decorator modifies a
method function so that it does not use the
self variable. The method function will not
have access to a specific instance of the class.
For an example of a static method, see the section called “Static Methods and Class Method”.
classmethod decorator modifies a
method function so that it receives the class object as the first
parameter instead of an instance of the class. This method
function wil have access to the class object itself.
is used to create singleton classes. This is a Python technique for
defining an object which is also a unique class. The class definition is
also the one and only instance. This gives us a very handy, easy-to-read
way to segregate attributes into a separate part of a class declaration.
This is a technique used heavily by Python frameworks.
Generally, a function decorated with
@classmethod is used for
introspection of a class. An introspection method
looks at the structure or features of the class, not the values of the
Here's a contrived example of using introspection to display some
features of a object's class.
Example 26.1. introspection.py
class SelfDocumenting( object ):
def getMethods( aClass ):
return [ (n,v.__doc__) for n,v in aClass.__dict__.items()
if type(v) == types.FunctionType ]
def help( self ):
"""Part of the self-documenting framework"""
class SomeClass( SelfDocumenting ):
attr= "Some class Value"
def __init__( self ):
"""Create a new Instance"""
self.instVar= "some instance value"
def __str__( self ):
"""Display an instance"""
return "%s %s" % ( self.attr, self.instVar )
We import the
types module to help
us distinguish among the various elements of a class
We define a superclass that includes two methods. The
getMethods, introspects a
class, looking for the method functions. The ordinary instance
help, uses the introspection to
print a list of functions defined by a class.
We use the
@classmethod decorator to
getMethods function. Making the
getMethods into a class method means that
the first argument will be the class object itself, not an
Every subclass of
can print a list of method functions using a
Here's an example of creating a class and calling the help method
we defined. The result of the
function is a list of tuples with method function names and
[('__str__', 'Display an instance'), ('__init__', 'Create a new Instance')]