← Back to list

🚨 Most Developers Get This Wrong: self vs @staticmethod vs @classmethod

Python Programming

Gdatawell · 2026-04-25 18:31 · 1 claps · 1.4 min read
#python #python-programming #interview #class-and-object #methods
Open on Medium ↗
Wiki topics: 💻 · Programming

🚨 Most Developers Get This Wrong: self vs @staticmethod vs @classmethod

Python Programming

Imagine You’re in an interview.

The interviewer leans forward and asks:

“In Python, when would you use self, @staticmethod, and @classmethod?”

If you start reciting definitions… you’ll lose them.

Instead, here’s how you answer like someone who actually knows Python:

Start Strong (Your Opening Line)

“It depends on what the method needs — object data, class data, or neither.”

That one line already sets you apart.

Step 1: Explain self (Instance Method)

“If the method needs data specific to an object, I use self.”

class User:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hi, I am {self.name}"

👉 Say this:

  • “Each object has its own state”
  • self lets me access or modify that state”.

Step 2: Explain @classmethod

“If the method works with class-level data, I use @classmethod.”

class Employee:
    company = "TCS"

    @classmethod
    def change_company(cls, name):
        cls.company = name

👉 Say this:

  • “It operates on the class, not individual objects”
  • “Useful for shared data or factory methods”.

Step 3: Explain @staticmethod

“If the method doesn’t need instance or class data, I use @staticmethod.”

class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b

👉 Say this:

  • “It’s logically related to the class but independent”
  • “Helps organize utility functions”

The One-Liner That Wins Interviews

self is for object behavior, cls is for class behavior, and static methods are for utility logic.”

If They Push Further…

They might ask:

“Why not just use a normal function instead of @staticmethod?”

Say this:

“You could, but keeping it inside the class improves readability and logical grouping — especially in larger codebases.”

Real-World Example (This Seals It)

“For example, in a data pipeline:”

  • self → process a specific dataset instance
  • @classmethod → create objects from configs (like JSON/YAML)
  • @staticmethod → validate or transform raw values

메타데이터
post_id
ac7850ea06f2
slug
most-developers-get-this-wrong-self-vs-staticmethod-vs-classmethod-ac7850ea06f2
url
https://medium.com/@Gayathri_krish/most-developers-get-this-wrong-self-vs-staticmethod-vs-classmethod-ac7850ea06f2
canonical_url
https://medium.com/@Gayathri_krish/most-developers-get-this-wrong-self-vs-staticmethod-vs-classmethod-ac7850ea06f2
author_url
https://medium.com/@Gayathri_krish
status
ok
fetched_at
2026-08-24 05:51:34