Python Static Methods
What is a Static Method in Python?
Definition:
A static method in Python is a method that belongs to a class rather than any instance of the class. It does not require access to instance (self) or class (cls) variables. It is defined using the @staticmethod decorator.
Key Features:
- Does not access or modify class/instance state
- Can be called using either the class name or instance
- Behaves like a normal function but lives in the class namespace
Syntax:
class MyClass:
@staticmethod
def static_function():
# function body
Example: Static Method Usage
class Calculator:
@staticmethod
def add(a, b):
return a + b
# Calling using class name
result = Calculator.add(10, 20)
print("Sum:", result)
Output:
Sum: 30
What is a Static Variable in Python?
Definition:
A static variable, also known as a class variable, is shared by all instances of a class. Unlike instance variables that are defined using self, static variables are defined inside the class but outside any method.
Example: Static Variable in Python
class Student:
school_name = "Green Valley High" # static variable
def __init__(self, name):
self.name = name # instance variable
s1 = Student("Alice")
s2 = Student("Bob")
print(s1.school_name)
print(s2.school_name)
Output:
Green Valley High Green Valley High
Updating Static Variable
Student.school_name = "Blue Mountain School"
print(s1.school_name) # Blue Mountain School
print(s2.school_name) # Blue Mountain School
Difference Between Static, Class, and Instance Methods
Feature | Instance Method | Class Method | Static Method |
---|---|---|---|
Access self? | Yes | No | No |
Access cls? | No | Yes | No |
Defined with | Regular def | @classmethod | @staticmethod |
Called by | Instance | Class or Instance | Class or Instance |
Example Combining All: Static Method, Static Variable, and Instance Method
class Bank:
bank_name = "National Bank" # static variable
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
def show_account(self): # instance method
print(f"{self.holder} - Balance: {self.balance}")
@staticmethod
def bank_info(): # static method
print("This is a national-level bank.")
# Create accounts
acc1 = Bank("Alice", 1000)
acc2 = Bank("Bob", 2000)
acc1.show_account()
acc2.show_account()
Bank.bank_info()
print("Bank Name:", Bank.bank_name)
Output:
Alice - Balance: 1000 Bob - Balance: 2000 This is a national-level bank. Bank Name: National Bank
Best Practices for Using Static Methods and Variables
- Use @staticmethod when your method doesn't access class or instance data
- Use static variables to store constants or shared values across instances
- Prefer instance methods when dealing with object-specific behavior