0Pricing
Python Academy · Lesson

Instance Methods and self

Write methods that operate on the object's own data.

Instance Methods and self is a free Python Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

Instance methods operate on the data of a specific object, using self to access and modify its attributes.

Defining Instance Methods

def method(self): inside a class is an instance method. It receives the object as the first argument (self).
class Circle:
    def __init__(self, r): self.r = r
    def area(self):
        import math
        return math.pi * self.r**2
print(Circle(5).area())

Calling Methods

obj.method() is syntactic sugar for ClassName.method(obj). Python passes obj as self automatically.
class Dog:
    def __init__(self, name): self.name = name
    def bark(self): print(f'{self.name} says Woof!')
Dog('Rex').bark()

Methods Returning self

Returning self enables method chaining: builder.set_name('x').set_age(3).build().
class Builder:
    def __init__(self): self.data = {}
    def set(self, k, v):
        self.data[k] = v
        return self
    def build(self): return self.data
result = Builder().set('x',1).set('y',2).build()
print(result)

Private Methods (Convention)

Prefix with _ to signal 'internal use'. Prefix with __ triggers name mangling: _ClassName__method.
class Account:
    def __init__(self, bal): self._bal = bal
    def _validate(self, amount): return amount > 0
    def deposit(self, amount):
        if self._validate(amount):
            self._bal += amount
a = Account(100)
a.deposit(50)
print(a._bal)

Properties as Methods

@property turns a method into a readable attribute. No parentheses needed when accessing.
class Circle:
    def __init__(self, r): self.r = r
    @property
    def diameter(self): return self.r * 2
c = Circle(5)
print(c.diameter)  # no ()

Mutating State

Methods that modify self attributes change the object's state. Design methods with clear intent: query vs command.
class Stack:
    def __init__(self): self.items = []
    def push(self, x): self.items.append(x)
    def pop(self): return self.items.pop()
    def peek(self): return self.items[-1]
s = Stack()
s.push(1); s.push(2)
print(s.pop(), s.peek())

Comparing Objects

By default == compares identity. Implement __eq__ to compare by value.
class Point:
    def __init__(self, x, y): self.x,self.y=x,y
    def __eq__(self, other): return self.x==other.x and self.y==other.y
print(Point(1,2)==Point(1,2))

Iteration Protocol

Implement __iter__ and __next__ to make a class iterable — usable in for loops.
class Countdown:
    def __init__(self, n): self.n = n
    def __iter__(self): return self
    def __next__(self):
        if self.n <= 0: raise StopIteration
        self.n -= 1; return self.n + 1
print(list(Countdown(3)))

Context Manager Protocol

Implement __enter__ and __exit__ to make a class usable in with statements.
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self
    def __exit__(self, *args):
        import time
        print(f'elapsed: {time.time()-self.start:.3f}s')
with Timer(): pass

Method vs Function

When accessed through the class, Dog.bark is a plain function. Through an instance, d.bark is a bound method — self is pre-filled.
class Dog:
    def bark(self): print('woof')
print(type(Dog.bark))
print(type(Dog().bark))

Quick Check

What is method chaining and what must a method return to support it?

Recap

Instance methods: def m(self). Call as obj.m(). return self for chaining. __eq__/__iter__/__enter__/__exit__ implement protocols. _ prefix signals internal use.

Keep Going

Excellent! Continue to the next lesson to deepen your skills.

Frequently asked questions

Is the “Instance Methods and self” lesson free?

Yes — the full text of “Instance Methods and self” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Instance Methods and self”?

Write methods that operate on the object's own data. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Instance Methods and self” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Classes and the __init__ Method
  2. Instance vs Class Attributes
  3. Instance Methods and self
  4. Magic Methods: __str__ and __repr__
← Back to Python Academy