Python has two built-in decorators.
-
@staticmethod
-
The 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
-
The 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.
The
@classmethod
decorator
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
specific instance.
Here's a contrived example of using introspection to display some
features of a object's class.
Example 26.1. introspection.py
import types
class SelfDocumenting( object ):
@classmethod
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"""
print self.getMethods()
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
definition.
|
|
We define a superclass that includes two methods. The
classmethod, getMethods , introspects a
class, looking for the method functions. The ordinary instance
method, help , uses the introspection to
print a list of functions defined by a class.
|
|
We use the
@classmethod decorator to
modify the getMethods function. Making the
getMethods into a class method means that
the first argument will be the class object itself, not an
instance.
|
|
Every subclass of SelfDocumenting
can print a list of method functions using a
help method.
|
Here's an example of creating a class and calling the help method
we defined. The result of the getMethods
method
function is a list of tuples with method function names and
docstrings.
>>>
ac= SomeClass()
>>>
ac.help()
[('__str__', 'Display an instance'), ('__init__', 'Create a new Instance')]