Skip to content

Python Methods, Initialization, and Introspection

Step 24 of 41

Python Methods, self, and Object Initialization

Introduction

Python instance methods receive the object as their first argument. A bound method remembers that object, so lamp.switch() supplies it automatically. An initializer uses the same mechanism to set up state after allocation; it must finish with a None return value.

This lesson covers PCAP-31-03 objectives 4.3 and 4.6 in Object-Oriented Programming (34% of the score, 12 of 40 items). You will trace required and default arguments, retained bound methods, failed initialization, and the inherited initializer used by a subclass.

Learning objectives

After this lesson you can:

  1. Explain that a method is a function stored in a class whose first parameter receives the instance.
  2. Distinguish a bound call (obj.method()) from an explicit call through the class (Class.method(obj)).
  3. Predict TypeError messages caused by a wrong number of arguments.
  4. Write __init__ with required, default and keyword arguments and use it to validate data.
  5. State the rules on the return value of __init__ and on classes without one.
  6. Describe how a subclass without its own __init__ inherits the parent's, and how an explicit parent call works.

Methods and self

For an ordinary instance method defined with def on a class, access through an instance binds that instance as the first argument. Its conventional parameter name is self. Static and class methods use different binding rules; the examples here are ordinary instance methods.

Python
class Ticket:
    def __init__(self, number, title):
        self.number = number
        self.title = title
        self.status = "open"

    def close(self):
        self.status = "closed"

    def summary(self):
        return f"#{self.number} {self.title} [{self.status}]"


t = Ticket(7, "Printer jams")
print(t.summary())      # #7 Printer jams [open]
t.close()
print(t.summary())      # #7 Printer jams [closed]

t.close() takes no argument in the call, yet the function definition has one parameter. Python supplies the instance automatically. The following table shows the two equivalent spellings:

Spelling What Python does Result
t.close() Looks up close on the class, binds t as the first argument Calls Ticket.close(t)
Ticket.close(t) Calls the plain function and passes t yourself Same effect
t.close(t) Passes t automatically, then once more TypeError: too many arguments
Ticket.close() No instance supplied TypeError: missing self

The name self is a convention, not a keyword. A method may call its first parameter this and still work, but self is the established convention. Trace a differently named parameter by its role rather than treating it as a keyword.

What self really is

self is an ordinary local variable that refers to the instance. Through it a method reads and writes attributes (self.status) and calls other methods (self.summary()). A bare name inside a method follows normal lexical scope rules: local, enclosing function scopes, global, and built-in. It does not automatically search the class namespace:

Python
class Counter:
    def __init__(self):
        self.value = 0

    def bump(self):
        value = self.value + 1     # a local variable named value
        self.value = value         # stores it in the instance


c = Counter()
c.bump()
c.bump()
print(c.value)     # 2

If the last line of bump were missing, the instance would never change: the local value disappears at the end of the call. Forgetting self. on an assignment is a classic bug, and a classic exam trap.

Argument counting

The number of parameters in the definition includes self; the number of arguments in a bound call does not.

Python
class Shelf:
    def put(self, item, qty=1):
        return f"{qty} x {item}"


s = Shelf()
print(s.put("bolt"))           # 1 x bolt
print(s.put("nut", 5))         # 5 x nut
print(s.put("washer", qty=3))  # 3 x washer
s.put()                        # TypeError: missing 1 required positional argument: 'item'
s.put("a", 1, 2)               # TypeError: Shelf.put() takes from 2 to 3 positional arguments but 4 were given

Note that the error message counts self: the last call reports four given arguments, because s is counted. The exam may show these messages or only ask which line fails; the rule to apply is "bound call = definition minus self".

Methods calling methods

Inside an instance method, use self.method() for normal method dispatch. A bare method name is not introduced into that method’s local scope by the class definition. Unless another binding supplies it, the bare call fails:

Python
class Report:
    def title(self):
        return "STOCK"

    def render(self):
        return self.title() + "!"      # correct
        # return title() + "!"         # NameError: name 'title' is not defined

Constructors: __init__

For the ordinary classes shown here, calling the class allocates an instance through __new__ and then initializes it through __init__. A custom allocator or metaclass can change that process; __init__ itself does not allocate or return the result object. The method name is fixed, with two underscores on each side. Its job is to initialise the object, so it normally creates attributes.

Python
class Product:
    def __init__(self, sku, price, currency="EUR"):
        self.sku = sku
        self.price = price
        self.currency = currency


a = Product("CH-1", 120)
b = Product("CH-2", 99.5, "USD")
c = Product(price=15, sku="LA-3")
print(a.currency, b.currency, c.currency)   # EUR USD EUR

All the usual argument rules apply: positional, keyword, default values. A default value is evaluated once, when the function is defined. This matters if the default is mutable; never write def __init__(self, items=[]), because every instance created without the argument would share the same list, a sharing problem similar to shared mutable class state, but here the list is held in the function’s default arguments. The usual idiom is a None default:

Python
class Bin:
    def __init__(self, items=None):
        self.items = [] if items is None else list(items)

Validation in the initializer

The initializer can reject invalid input. If it raises during normal construction, that class call fails and its result is not assigned. It does not undo earlier side effects or references that the initializer may already have exposed:

Python
class Quantity:
    def __init__(self, amount):
        if amount < 0:
            raise ValueError("amount must not be negative")
        self.amount = amount


ok = Quantity(5)
bad = Quantity(-1)      # ValueError; no object is assigned to bad

In this fresh snippet, bad is not bound because the right-hand side fails. If bad already referred to an earlier object, that binding would remain unchanged.

Rules on __init__

Rule Consequence
__init__ must return None Returning another value raises TypeError: __init__() should return None
A class can inherit __init__ Accepted arguments depend on the inherited construction methods
Ordinary successful construction invokes the selected initializer Custom allocation or explicit reinitialization requires separate tracing
It receives the instance as self Attributes assigned to self become instance variables
It may be called explicitly obj.__init__(...) re-runs it on an existing object (rare, and legal)

For class Plain: pass, which inherits the default construction methods from object, Plain() works and Plain(1) raises TypeError. A subclass inheriting a custom initializer can accept arguments without defining its own. Many exam items check precisely this.

Constructors and inheritance

A subclass that does not define __init__ inherits the parent's one. This is covered fully in chapter 10; the essential facts for this lesson are:

Python
class Asset:
    def __init__(self, tag):
        self.tag = tag


class Laptop(Asset):
    pass


l = Laptop("LT-42")
print(l.tag)       # LT-42

The call Laptop("LT-42") runs the inherited Asset.__init__. If the subclass defines its own __init__, the parent's initializer is not called automatically. You must call it explicitly:

Python
class Laptop(Asset):
    def __init__(self, tag, ram):
        Asset.__init__(self, tag)      # run the parent initialisation
        self.ram = ram


class Phone(Asset):
    def __init__(self, tag, number):
        self.number = number           # parent initializer forgotten


print(Laptop("LT-1", 16).tag)          # LT-1
print(Phone("PH-1", "555").number)     # 555
print(Phone("PH-1", "555").tag)        # AttributeError: no attribute 'tag'

Asset.__init__(self, tag) calls the parent's function through the class and passes the instance by hand, which is the "explicit call" row of the table above. In this single-parent example, super().__init__(tag) reaches the same initializer without naming Asset. In multiple inheritance, super() searches after the lexical class in the instance’s MRO and can reach a sibling. See subclass initialization and method overriding before treating the two forms as interchangeable.

Bound methods are values

Because functions are objects, a bound method can be stored in a variable, put in a list or passed to another function. The instance travels with it:

Python
class Lamp:
    def __init__(self, name):
        self.name = name
        self.on = False

    def switch(self):
        self.on = not self.on
        return f"{self.name}: {'on' if self.on else 'off'}"


desk = Lamp("desk")
hall = Lamp("hall")

action = desk.switch          # no parentheses: nothing is called yet
print(action())               # desk: on
print(action())               # desk: off
print(hall.switch())          # hall: on

handlers = [desk.switch, hall.switch]
print([h() for h in handlers])   # ['desk: on', 'hall: off']

action remembers desk. Calling it twice toggles the same lamp twice, and hall is never affected. The last line shows that the order of calls matters: desk was off after two toggles, so it turns on again, while hall was switched on one line earlier and now turns off.

The unbound form is the plain function taken from the class, which needs the instance explicitly:

Python
f = Lamp.switch
print(f(desk))                # desk: off (it was on after the handlers ran)

Writing f() with no argument would raise TypeError, because nothing supplies self. An exam item may present both forms side by side and ask which call succeeds; the one that already carries an instance (taken from an object) needs no argument, and the one taken from the class needs exactly one more.

Methods that return self

A method may return self, which allows calls to be chained. This is a style choice, not a rule, but it appears in code-reading questions:

Python
class Builder:
    def __init__(self):
        self.parts = []

    def add(self, part):
        self.parts.append(part)
        return self


b = Builder().add("base").add("walls").add("roof")
print(b.parts)       # ['base', 'walls', 'roof']

Each add returns the same object, so the next call works on it. If add returned nothing, the second call would try to look up add on None and raise AttributeError.

Worked example: validated service tickets

Statement. A help desk creates tickets with a priority between 1 and 3. Trace the successful ticket creations and the final invalid one. Give the printed lines and identify the exception that follows.

Python
class ServiceTicket:
    created = 0

    def __init__(self, title, priority=2):
        if priority not in (1, 2, 3):
            raise ValueError("priority must be 1, 2 or 3")
        self.title = title
        self.priority = priority
        self.notes = []
        ServiceTicket.created += 1

    def add_note(self, text):
        self.notes.append(text)
        return len(self.notes)

    def summary(self):
        return f"{self.title} (P{self.priority}, {len(self.notes)} notes)"


first = ServiceTicket("VPN down", 1)
second = ServiceTicket("New keyboard")
print(first.add_note("called user"))
print(first.add_note("restarted client"))
print(second.add_note("order placed"))
print(first.summary())
print(second.summary())
print(ServiceTicket.created)
third = ServiceTicket("Broken", 5)
print("unreachable")

Step 1: the constructor calls. first receives priority 1. second uses the default priority 2. Each call runs the validation (both pass), creates its own notes list and increments the class counter.

Step 2: the notes. Each add_note appends to the list of the object it is called on and returns that list's new length. first gets two notes (printing 1 then 2). second has its own list and gets one (printing 1). The lists are independent, because they are created in __init__.

Step 3: the summaries and the counter. first.summary() gives VPN down (P1, 2 notes). second.summary() gives New keyboard (P2, 1 notes). The counter has been incremented twice.

Step 4: the failing line. ServiceTicket("Broken", 5) raises ValueError before any attributes or counter updates in that initializer. The outer assignment to third never completes, and "unreachable" is never printed.

Text
1
2
1
VPN down (P1, 2 notes)
New keyboard (P2, 1 notes)
2
ValueError: priority must be 1, 2 or 3

Why other choices are weaker. An answer that prints 3 for the third add_note assumes the two tickets share one list; the list is created per instance in __init__. An answer that expects the counter to reach 3 forgets that the third constructor call raises before its increment, and the counter was printed earlier anyway. Finally, moving the ServiceTicket.created += 1 line above the check would change the counter to count failed attempts, which is a design decision worth noticing when you read a constructor.

Common pitfalls and exam tips

Pitfall Symptom Remedy
Forgetting self in the definition TypeError: takes 0 positional arguments but 1 was given on the bound call Every instance method needs the first parameter
Writing value = x instead of self.value = x The attribute is never stored Look for the self. prefix on every assignment
Calling a sibling method without self. NameError Use self.method()
Mutable default argument All instances share one list Use None and create the list inside
Returning a non-None value from __init__ TypeError Use return None, a bare return, or normal fall-through
Overriding __init__ without calling the parent Parent attributes missing Call Parent.__init__(self, ...) or super().__init__(...)
Counting self as a call argument Wrong argument count in the answer Bound calls pass self for you

Exam tip. For a "does this line raise an error?" item, first count parameters minus self, then compare with the arguments given, then check for defaults.

Exam tip. If a constructor raises, the assignment on that line never happens. A later use of the name gives NameError, or the previous object if the name was already bound.

Exam tip. When the subclass defines __init__ and the parent attribute is later read, search the subclass initializer for a call to the parent. If you do not find one, the attribute probably does not exist.

End-of-lesson case study

Situation. A training platform stores enrolments. The developer wrote the code below and finds that every enrolment of a course starts with the notes of the previous ones, and that Premium objects crash on price. Diagnose both problems and give the corrected classes.

Python
class Enrolment:
    def __init__(self, student, notes=[]):
        self.student = student
        self.notes = notes

    def note(self, text):
        self.notes.append(text)


class Premium(Enrolment):
    def __init__(self, student, price):
        self.price = price


e1 = Enrolment("Mia")
e2 = Enrolment("Noah")
e1.note("asked for extension")
print(e2.notes)

p = Premium("Lea", 99)
print(p.price)
print(p.student)

Solution, commented. The default notes=[] is created once when the function is defined, so e1 and e2 receive the same list. e1.note(...) appends to it, and print(e2.notes) shows ['asked for extension']. The fix is notes=None with self.notes = [] if notes is None else list(notes).

Premium defines its own __init__ and never calls the parent's, so p.price prints 99 but p.student raises AttributeError: the attribute was never created. The price read does not crash as the developer thought; the crash is on student. The fix is super().__init__(student) (or Enrolment.__init__(self, student)) as the first line of the subclass initializer. With both fixes, each newly created enrolment has its own outer list and p.student returns "Lea". A complete corrected version is:

Python
class Enrolment:
    def __init__(self, student, notes=None):
        self.student = student
        self.notes = [] if notes is None else list(notes)

    def note(self, text):
        self.notes.append(text)


class Premium(Enrolment):
    def __init__(self, student, price):
        super().__init__(student)
        self.price = price

Key terms

  • Method: a function defined in a class whose first parameter receives the instance.
  • self: the conventional name of that first parameter.
  • Bound call: a call written obj.method(...), where Python supplies the instance.
  • Initializer (__init__): sets up an already allocated instance; __new__ performs allocation during ordinary construction.
  • Default argument: a value used when the caller gives none, evaluated once at definition time.
  • Explicit parent call: Parent.__init__(self, ...) or super().__init__(...).

Summary checklist

  • I know that obj.method(a) means Class.method(obj, a).
  • I can count arguments correctly for bound and unbound calls.
  • I know that attributes need the self. prefix to survive the call.
  • I can write __init__ with defaults and validation.
  • I know __init__ must return None and inspect inherited initialization before deciding which arguments a class accepts.
  • I avoid mutable default arguments.
  • I know a subclass __init__ does not call the parent's automatically.

Official sources