Static Methods and Class Method
In a few cases, our class may have methods which depend on only
the argument values, or only on class variables. In this case, the
self
variable isn't terribly useful, since the method
doesn't depend on any attributes of the instance. Objects which depend
on argument values instead of internal status are called
Lightweight
or
Flyweight
objects.
A method which doesn't use the self
variable is
called a static method. These are defined using a built-in function
named staticmethod
. Python has a handy syntax,
called a decorator, to make it easier to apply the
staticmethod
function to our method function
definition. We'll return to decorators in Chapter 26, Decorators
.
Here's the syntax for using the staticmethod
decorator.
def
name
(args...)
:
suite
To evaluate a static method function, we simply reference the
method of the class:
Class
.
method
()
.
Example of Static Method. Here's an example of a class which has a static method. We've
defined a deck shuffler. It doesn't have any attributes of its own.
Instead, it applies it's shuffle
algorithm to
a Deck
object.
class Shuffler( object ):
@staticmethod
def shuffle( aDeck ):
for i in range(len(aDeck)):
card= aDeck.get( random.randrange(len(aDeck)) )
aDeck.put( i, card )
d1= Deck()
Shuffler.shuffle( d1 )
Class Method. The notion of a class method is relatively specialized. A class
method applies to the class itself, not an instance of the class. A
class method is generally used for "introspection" on the structure or
definition of the class. It is commonly defined by a superclass so
that all subclasses inherit the necessary introspection
capability.
Generally, class methods are defined as part of sophisticated,
dynamic frameworks. For our gambling examples, however, we do have some
potential use for class methods. We might want to provide a base
Player
class who interacts with a particular
Game
to make betting decisions. Our superclass
for all players can define methods that would be used in a
subclass.