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.
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?
selfis 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 thedefline. - It is only a name. You could call it
this, butselfis the community standard. - Real-life: when Asha says "my roll number", "my" means Asha.
selfis 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 upintroduceon the class and creates a bound method withashaalready filled asself.Student.introduce(asha)does the same work explicitly.- Forgetting
selfin 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
| Use | Example | Purpose |
|---|---|---|
| Read/write attributes | self.balance += amt | Work with this object's state |
| Call other methods | self.validate() | Reuse behaviour on same object |
| Pass current object | registry.add(self) | Register / link objects |
| Return current object | return self | Fluent / chained calls |
| Clarify shadowing | self.name = name | Field vs parameter |
Shadowing: self.name = name
- Parameters often reuse attribute names. Without
self., assignment updates the local name only. self.name = namestores 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
selflets callers writeobj.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
| Kind | First parameter | Typical call |
|---|---|---|
| Instance method | self (instance) | obj.method() |
| Class method | cls (class) | Class.method() or obj.method() |
| Static method | None special | Class.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
selfin the parameter list. - Writing
name = namein__init__instead ofself.name = name. - Trying to use
selfinside a@staticmethodor at class level outside methods.
class Ok:
def __init__(self, value):
self.value = value
def show(self):
print(self.value)
Ok(7).show() Advanced — self Keyword
Bound methods are objects
obj.methodwithout parentheses is a bound method object.- You can store it and call it later;
selfremains 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
selfis 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,
selfmay 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 sameself.
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
isto 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.
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.
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)) Problem Solving Tricks
- Always write
selfas the first parameter of instance methods — including__init__. self.name = nameis the standard way to store constructor arguments.obj.method()≈Class.method(obj).- Return
selfonly when chaining is the API you want. - Use
clsin classmethods; do not pretend they receive an instance as self. - Store bound methods for callbacks without writing extra lambdas.
- Prefer
isfor identity checks; avoid printing rawid()values. - If you see "takes 0 positional arguments but 1 was given", you probably forgot
self. - Keep helper methods and call them via
selfto share validation. - Name it
selfeven though Python allows other names — readers expect it.
Practice Programs List
- Write
Student.introduceand call it on two different objects. - Build a fluent
Query.select(...).where(...).build()API. - Create
Accountwith private helper_ensure_positiveused by deposit/withdraw. - Save a bound method in a list and call it twice as a callback.
- Call the same method once via
obj.m()and once viaClass.m(obj). - Demonstrate a bad
__init__that assignsname = namewithoutselfand then fix it. - Write a mini builder for a sandwich or pizza using chained methods.
- Show polymorphism: parent method uses
type(self).__name__with two subclasses. - Compare
a is bvs equal field values for two separately constructed objects. - Refactor duplicated validation into a method called through
self. - Explain in comments why staticmethods do not receive self.
- List six uses of self and implement a tiny example for three of them.