staticmethod
Consider a class
. We create an instance of the class
. But some features of the class
may not require an instance—they are more general-purpose.
This is where a static
method is needed. A static
method (indicated with staticmethod
) means the method is called on the type name, not an instance.
This is a function decorator. We apply it by specifying classmethod
before "def
." It is a combination of an instance, and static
, method. It can be called either way.
classmethod
example, with the syntax Box.example
or on a Box instance "b".class
argument ("cls" here) can be used as to create a type and return it. Or we can ignore it.class Box:
@classmethod
def example(cls, code):
# This method can be used as an instance or static method.
print("Method called:", code)
# Use classmethod as a static method.
Box.example("cat")
# Use classmethod as an instance method.
b = Box()
b.example("dog")Method called: cat
Method called: dog
A static
method accepts no self
-instance. Most methods in a class
accept a first argument with name self
. With the staticmethod
decorator, though, we omit this argument.
class
name, or on an instance.static
method with Box.Message
or on an instance like b.Message
.class Box:
@staticmethod
def Message(a):
print("Box Message", a)
# Call static method with type.
Box.Message(1)
# Call static method with instance.
b = Box()
b.Message(2)Box Message 1
Box Message 2
Class
methods and static
methods are useful in Python programs. Often a class
has parts to it that are not instance-based. Requiring an instance would be cumbersome and awkward.