@staticmethod?

What is a @staticmethod?

  • It’s a method inside a class

  • But it doesn’t use self or cls

  • 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 self or cls involved


Recap Table

Call From

Works?

Example

Parent class

BankAccount.is_valid_account_number(...)

Subclass

SavingsAccount.is_valid_account_number(...)

Subclass object

acc.is_valid_account_number(...)


Summary:

Feature

Description

Decorator

@staticmethod

Access to self?

❌ No

Access to cls?

❌ No

Use for

Utility/helper method inside the class

Call using

ClassName.method()

Updated on