Classmethod, 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.
Classmethod. 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.
So We can call the classmethod example, with the syntax Box.example or on a Box instance "b."
Detail The 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
Staticmethod. 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.
Tip Static methods can return any value. They can accept any arguments. They are called with the class name, or on an instance.
Also It makes no difference whether you call a 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
A review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 14, 2023 (edit link).