Python classmethod and staticmethod UseUse the classmethod and staticmethod decorators on functions.
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.Class
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.Built-ins
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."
Class: The class argument ("cls" here) can be used as to create a type and return it. Or we can ignore it.
Python program that uses 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.
# Use classmethod as an instance method.
b = Box()
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.
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.
Python program that uses staticmethod
print("Box Message", a)
# Call static method with type.
# Call static method with instance.
b = Box()
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.