Nearby lessons

105 of 159

Python - Static Methods

📌 What You Will Learn
  • Understand what a static method is
  • Use the @staticmethod decorator
  • Know that static methods do not require self or cls
  • Call static methods using the class name or an object reference

What Is a Static Method?

A static method is a method that does not use self or cls.

It is usually used for utility operations that do not depend on object or class data.

Syntax

The @staticmethod decorator tells Python that the method belongs to the class but does not require an object or class reference.

🐍Code Cell
1class Demo:
2 
3 @staticmethod
4 def add(x, y):
5 return x + y
Output
No output captured.

Example

Static methods are commonly written inside a math or utility class.

🐍Code Cell
1class DurgaMath:
2 
3 @staticmethod
4 def add(x, y):
5 print("The Sum:", x + y)
6 
7 @staticmethod
8 def multiply(x, y):
9 print("The Product:", x * y)
10 
11 
12DurgaMath.add(10, 20)
13DurgaMath.multiply(10, 20)
Output
The Sum: 30
The Product: 200

Calling Through Object

Although it is recommended to call a static method using the class name, it can also be called through an object reference.

🐍Code Cell
1class Test:
2 
3 @staticmethod
4 def display():
5 print("Static Method")
6 
7 
8t = Test()
9t.display()
Output
Static Method

Important Points

  • Use the @staticmethod decorator.
  • No implicit self or cls parameter.
  • Can be called using the class name or object reference.

Summary

Term Meaning
@staticmethodDefines a static method
selfNot required
clsNot required
📝 Key Takeaways
  • A static method is a method that does not use self or cls
  • It is defined using the @staticmethod decorator
  • It is usually used for general utility operations
  • It can be called using the class name or an object reference

🧠 Test Your Knowledge

6 Questions
Progress: 0 / 6