self

What is self in Python?

Suppose you go to a family function... Everyone’s calling each other “beta”, “bhai”, “didi”...

But how do you know they’re talking about YOU?

That’s where self comes in.

In Python classes, self is like saying "me, this exact object."


🔹 What does self mean?

  • It refers to the current object of the class

  • Let’s you access that object’s own data and methods

  • It’s automatically passed in every method (you don’t have to pass it manually)


💡 Example

class BankAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

    def show_info(self):
        print(f"Account holder: {self.name}")
        print(f"Balance: {self.balance}")

Now if you create:

acc1 = BankAccount("Maham", 1000)
acc1.show_info()

Output:

Account holder: Maham  
Balance: 1000

🔍 Why did it print Maham?

Because:


🧠 Why Not Just Use name Instead of self.name?

  • Without self, Python thinks name is just a local variable

  • With self.name, you’re saying → this belongs to the object itself

Like:

self.name = name

Left side → object variable
Right side → local input from constructor


🔄 Can We Name It Anything Else?

Technically yes. You can write:

def __init__(banana, name):
    banana.name = name

But please don’t.
Everyone in Python uses self. It's a standard.


🧪 When and Where to Use self

Use case

Need self?

Why

Set property in constructor

✅ Yes

Object-level variable

Access method inside class

✅ Yes

Belongs to the object

Call static/class method

❌ No

They don’t use object

Outside class?

❌ No

You use object name


🤔 Common Questions You May Have

  • Is self a keyword?
    → No. Just a naming convention (but must be first argument)

  • Do I always need to write self in methods?
    → Yes, in instance methods (normal methods)

  • Can I access self.property in another method?
    → Yes! That's the whole point of using self — so data stays with the object

  • What about class-level variables?
    → Those are accessed with ClassName.property or self.__class__.property


🚫 Don’t Confuse

Wrong

Why wrong

Fix it

balance = 100 inside method

Local only, not saved

Use self.balance = 100

print(name) inside class

No such variable

Use self.name


🧶 Summary in One Line

self is how an object talks to itself.

Simple. Clean. Py-thonic.


Stay Connected - @syedamahamfahim 🐬

Updated on