Skip to main content

Python OOP

self Keyword

Complete lesson for self Keyword using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — self Keyword

Section: Python OOP. The Python self parameter — the current instance. How binding works, why self is explicit, shadowing, chaining, and class/static differences.

What is self?

  • self is the conventional name for the first parameter of an instance method: the object the method was called on.
  • Python passes it automatically when you write obj.method(...). You still declare it in the def line.
  • It is only a name. You could call it this, but self is the community standard.
  • Real-life: when Asha says "my roll number", "my" means Asha. self is that "my" for an object.
class Student:
    def __init__(self, name):
        self.name = name

    def introduce(self):
        print("My name is", self.name)

asha = Student("Asha")
ravi = Student("Ravi")
asha.introduce()
ravi.introduce()

How binding works

  • asha.introduce() looks up introduce on the class and creates a bound method with asha already filled as self.
  • Student.introduce(asha) does the same work explicitly.
  • Forgetting self in the definition is a common beginner error: Python will complain about missing arguments.
class Counter:
    def __init__(self):
        self.n = 0

    def bump(self):
        self.n += 1
        return self.n

c = Counter()
print(c.bump())
print(Counter.bump(c))
print(c.n)

Uses of self

UseExamplePurpose
Read/write attributesself.balance += amtWork with this object's state
Call other methodsself.validate()Reuse behaviour on same object
Pass current objectregistry.add(self)Register / link objects
Return current objectreturn selfFluent / chained calls
Clarify shadowingself.name = nameField vs parameter

Shadowing: self.name = name

  • Parameters often reuse attribute names. Without self., assignment updates the local name only.
  • self.name = name stores the parameter into the instance attribute.
  • This pattern appears in almost every __init__.
class Player:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def rename(self, name):
        self.name = name

p = Player("Neo", 100)
p.rename("Trinity")
print(p.name, p.health)

Calling other methods through self

  • Inside a method, call siblings as self.other().
  • That keeps the same instance in play and avoids hard-coding the class name.
  • Useful for splitting validation, formatting, and core logic.
class Invoice:
    def __init__(self, items):
        self.items = list(items)

    def subtotal(self):
        return sum(self.items)

    def tax(self):
        return self.subtotal() * 0.18

    def total(self):
        return self.subtotal() + self.tax()

inv = Invoice([100, 50, 50])
print(inv.subtotal(), round(inv.tax(), 2), round(inv.total(), 2))

Returning self for chaining

  • Returning self lets callers write obj.a().b().c().
  • Common in builders and configuration APIs.
  • Each method should still do one clear job.
class Query:
    def __init__(self):
        self.parts = []

    def select(self, cols):
        self.parts.append("SELECT " + cols)
        return self

    def where(self, cond):
        self.parts.append("WHERE " + cond)
        return self

    def build(self):
        return " ".join(self.parts)

sql = Query().select("name, age").where("age >= 18").build()
print(sql)

self vs cls vs no first special arg

KindFirst parameterTypical call
Instance methodself (instance)obj.method()
Class methodcls (class)Class.method() or obj.method()
Static methodNone specialClass.method() / obj.method()
class Demo:
    def instance_hi(self):
        print("instance", type(self).__name__)

    @classmethod
    def class_hi(cls):
        print("class", cls.__name__)

    @staticmethod
    def static_hi():
        print("static")

Demo().instance_hi()
Demo.class_hi()
Demo.static_hi()

Common self mistakes

  • Forgetting self in the parameter list.
  • Writing name = name in __init__ instead of self.name = name.
  • Trying to use self inside a @staticmethod or at class level outside methods.
class Ok:
    def __init__(self, value):
        self.value = value

    def show(self):
        print(self.value)

Ok(7).show()
L2

Advanced — self Keyword

Bound methods are objects

  • obj.method without parentheses is a bound method object.
  • You can store it and call it later; self remains fixed.
  • Useful for callbacks: button.on_click = obj.handle.
class Adder:
    def __init__(self, base):
        self.base = base

    def add(self, n):
        return self.base + n

a = Adder(10)
fn = a.add
print(fn(5))
print(fn(8))

Explicit Class.method(obj) form

  • Calling via the class requires you to pass the instance manually.
  • This form appears in super() discussions and some functional-style code.
  • It also proves that self is just the first argument.
class Greeter:
    def hello(self, title):
        return f"{title} {self.name}"

g = Greeter()
g.name = "Asha"
print(g.hello("Hi"))
print(Greeter.hello(g, "Hello"))

self and inheritance

  • In a subclass method, self may be an instance of the subclass even when the method body lives on the parent.
  • That is how polymorphism works: the same method code cooperates with different concrete objects.
  • super() helpers still operate with the same self.
class Animal:
    def speak(self):
        return f"{type(self).__name__} speaks"

class Dog(Animal):
    def speak(self):
        return f"{type(self).__name__} barks"

print(Animal().speak())
print(Dog().speak())

Identity without printing addresses

  • Use is to test whether two names refer to the same object.
  • Do not rely on printing id(...) in tutorials or production logs.
  • Equality (==) can be customized; identity (is) cannot.
class Tag:
    def __init__(self, label):
        self.label = label

a = Tag("x")
b = a
c = Tag("x")
print(a is b)
print(a is c)
print(a.label == c.label)

Fluent APIs and when not to chain

  • Chaining is great for builders that mutate and return self.
  • If a method naturally returns a new value (like total()), return that value instead of self.
  • Mixed styles confuse readers: pick fluent or command/query separation deliberately.
L3

Tricky Interview Points

Q1) What is self in Python?

Answer The conventional first parameter of an instance method, referring to the instance on which the method was called.

Q2) Is self a keyword?

Answer No. It is a strong convention. Python does not reserve the name self, but you should still use it.

Q3) Why must we write self in the method definition?

Answer Because instance methods receive the instance as an explicit first argument. The definition must declare that parameter.

Q4) What happens if you omit self in def?

Answer Calling obj.method() still passes the instance, so you get TypeError: method() takes 0 positional arguments but 1 was given (message may vary slightly).

Q5) Difference between self and cls?

Answer self is an instance. cls in a @classmethod is the class object (useful for factories and alternate constructors).

Q6) How does obj.method() supply self?

Answer Attribute lookup returns a bound method that remembers obj and inserts it as the first argument when called.

Q7) Can methods return self?

Answer Yes. That enables fluent chaining such as obj.set_x(1).set_y(2).

Q8) Can static methods use self?

Answer No special self is passed. A static method is like a plain function living in the class namespace.

Q9) How do you access attributes inside a method?

Answer Through self, for example self.name or self.total().

Q10) Real-life analogy for self?

Answer Like saying "my" — the meaning depends on who is speaking. Each object's methods see that object as self.

Q11) What is a bound method?

Answer A callable that already has the instance attached, created when you access an instance method via an instance.

Q12) Does self work in __init__?

Answer Yes. __init__ is an instance method; self is the newly created object being initialized.

L4

Simple Programs

Introduce two students via self

class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll

    def introduce(self):
        print(f"I am {self.name}, roll {self.roll}")

Student("Asha", 1).introduce()
Student("Ravi", 2).introduce()

Fluent burger builder

class Burger:
    def __init__(self):
        self.parts = ["bun"]

    def add_patty(self):
        self.parts.append("patty")
        return self

    def add_cheese(self):
        self.parts.append("cheese")
        return self

    def add_veg(self):
        self.parts.append("veg")
        return self

    def build(self):
        self.parts.append("bun")
        return " + ".join(self.parts)

print(Burger().add_patty().add_cheese().add_veg().build())

Bank operations using self helpers

class Account:
    def __init__(self, holder, balance=0):
        self.holder = holder
        self.balance = balance

    def _ensure_positive(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")

    def deposit(self, amount):
        self._ensure_positive(amount)
        self.balance += amount

    def withdraw(self, amount):
        self._ensure_positive(amount)
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount

acc = Account("Priya", 1000)
acc.deposit(200)
acc.withdraw(100)
print(acc.holder, acc.balance)

Bound method as callback

class Logger:
    def __init__(self, prefix):
        self.prefix = prefix

    def log(self, message):
        print(f"[{self.prefix}] {message}")

logger = Logger("app")
handlers = [logger.log]
for h in handlers:
    h("started")
    h("ready")

Explicit class call vs bound call

class Multiplier:
    def __init__(self, factor):
        self.factor = factor

    def apply(self, n):
        return self.factor * n

m = Multiplier(3)
print(m.apply(4))
print(Multiplier.apply(m, 4))

Polymorphism with self

class Shape:
    def tag(self):
        return type(self).__name__

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14159 * self.r * self.r

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

shapes = [Circle(2), Square(3)]
for s in shapes:
    print(s.tag(), round(s.area(), 2))
L5

Problem Solving Tricks

  • Always write self as the first parameter of instance methods — including __init__.
  • self.name = name is the standard way to store constructor arguments.
  • obj.method() ≈ Class.method(obj).
  • Return self only when chaining is the API you want.
  • Use cls in classmethods; do not pretend they receive an instance as self.
  • Store bound methods for callbacks without writing extra lambdas.
  • Prefer is for identity checks; avoid printing raw id() values.
  • If you see "takes 0 positional arguments but 1 was given", you probably forgot self.
  • Keep helper methods and call them via self to share validation.
  • Name it self even though Python allows other names — readers expect it.
L6

Practice Programs List

  1. Write Student.introduce and call it on two different objects.
  2. Build a fluent Query.select(...).where(...).build() API.
  3. Create Account with private helper _ensure_positive used by deposit/withdraw.
  4. Save a bound method in a list and call it twice as a callback.
  5. Call the same method once via obj.m() and once via Class.m(obj).
  6. Demonstrate a bad __init__ that assigns name = name without self and then fix it.
  7. Write a mini builder for a sandwich or pizza using chained methods.
  8. Show polymorphism: parent method uses type(self).__name__ with two subclasses.
  9. Compare a is b vs equal field values for two separately constructed objects.
  10. Refactor duplicated validation into a method called through self.
  11. Explain in comments why staticmethods do not receive self.
  12. List six uses of self and implement a tiny example for three of them.