Sometimes you want to associate a function with a particular
class, but it doesn't always have an instance
(self) to operate on. In these
cases, you can declare a static
method within the class. Such a method is
like any other method, except that you won't include
a first argument of self in the
argument list. To make a method static, include a line
of this form just after the method's declaration:
f= staticmethod (f)
where
is the
name of the method.f
To call a static method, use this syntax:
C.f(...)
where
is the
class name and C is the method name.f
Here's an example. Suppose you have a class called
Celsius that represents a
temperature, and you want to be able to convert an object
of that class to a 6-character string for display. Normally
you would declare a .__str__() method
in the class to do the conversion.
However, suppose you have a variable named
outdoor that may contain a
Celsius object, but sometimes the
temperature is unknown and outdoor
is set to None. You want to write
a function that will convert the temperature if it is
known, but render the value as '******'
if not. You could write a standalone function that does
that, but it really is associated with the class. So you
write a static function like this:
class Celsius:
...
def show(temp):
if temp is None:
return '******'
else:
return str(temp)
show = staticmethod(show)Then you could call this method as
"Celsius.show(outdoor)".