@staticmethod
- id: 1739549603
- Date: Feb. 15, 2025, 5:18 p.m.
- Author:
- Goals
- Describe this decorator.
- Skillfully use it
@staticmethod (What)
@staticmethod is a built-in Python decorator used to define a method inside a class that does not depend on an instance (self) or the class (cls). It belongs to the class but does not interact with instance attributes or methods. It is a helper function
Key Characteristics:
- Does not require self (instance) or cls (class) as the first parameter.
- Can be called directly on the class without creating an instance.
- Used for utility/helper functions related to the class but not dependent on its attributes.
Example
class MyClass:
@staticmethod
def my_static_method(arg1, arg2):
return arg1 + arg2
result = MyClass.my_static_method(3, 5)
print(result) # Output: 8
When to Use @staticmethod?
Use @staticmethod when: • The method does not need to modify or access instance (self) or class (cls) attributes. • The method logically belongs to the class but doesn’t depend on instance data. • You want a method inside a class that behaves like a regular function but is namespaced inside the class.
Example: Without @staticmethod (Incorrect Use)
class MathOperations: def add(x, y): # Missing self, but this is not a static method return x + y
If you try MathOperations().add(2, 3), Python will throw an error because self is expected.
Example: With @staticmethod (Correct Use)
class MathOperations: @staticmethod def add(x, y): return x + y
print(MathOperations.add(2, 3)) # ✅ Works fine: Output 5
Summary
- @staticmethod allows defining functions
inside a class without needing self or cls.
- It is useful for utility functions related to a class but not tied to an instance.
- It saves memory by not binding the method to instances.
- You can call it using ClassName.method_name().