Static methods in Python
Static methods are similar to instance methods (class-level methods), except static methods behave like regular functions bound to a class namespace. Unlike instance methods, static methods do not have access to cls
or self
.
Creating static methods
A class named StringUtil
contains a is_empty
method for determining if a string is empty.
1class StringUtil:
2 @staticmethod
3 def is_empty(s):
4 return not s.strip()
5
6print(StringUtil.is_empty("test")) # False
7print(StringUtil.is_empty(" ")) # True
When to use static methods
Static methods are advantageous for:
- Singletons
- Utility classes with similar grouped methods
- Methods that belong in a class namespace, but do not require instance variables (
self
)