What is a @staticmethod?
-
It’s a method inside a class
-
But it doesn’t use
selforcls -
It means: No need for object or class-level data
Why do we use it?
Sometimes, you just want a utility/helper function related to the class,
But that function doesn’t need to access any property
Example: Bank Account Number Checker
Suppose you're working on a banking app.
You want to make sure that every account number should
-
Start with 1
-
Have exactly 10 digits
Now, this rule doesn’t need:
-
Holder name
-
Balance
-
Interest rate
So we don't need self or cls
Just a plain rule
Code:
class BankAccount:
@staticmethod
def is_valid_account_number(number):
return str(number).startswith("1") and len(str(number)) == 10
Use It:
print(BankAccount.is_valid_account_number(1234567890)) # ✅ True
print(BankAccount.is_valid_account_number(9876543210)) # ❌ False
-
No need to create a BankAccount object
-
Just use class name to call it
@staticmethod — in subclass and object
even if it’s inside a parent class, you can use it like this:
1. Using class name (as usual)
BankAccount.is_valid_account_number("1234567890") # ✅ works
2. Using subclass name
class SavingsAccount(BankAccount):
pass
SavingsAccount.is_valid_account_number("1234567890") # ✅ works
3. Using the object of a subclass
acc = SavingsAccount()
acc.is_valid_account_number("1234567890") # ✅ works too
yes yes, even from object it works
because the static method is like a normal function, just attached to class
so Python allows calling it from the object, even if it doesn’t use object data
But remember:
-
It doesn't care which class or object you used to call it
-
It just runs the same code inside
-
No
selforclsinvolved
Recap Table
Call From | Works? | Example |
|---|---|---|
Parent class | ✅ |
|
Subclass | ✅ |
|
Subclass object | ✅ |
|
Summary:
Feature | Description |
|---|---|
Decorator |
|
Access to | ❌ No |
Access to | ❌ No |
Use for | Utility/helper method inside the class |
Call using |
|