1. Concept library
  2. Python Foundations
  3. Module 9: Classes and objects

Concept

Methods and self

A method is a function defined in a class. Its first parameter, self, is the instance it was called on, which is how a method reads and changes that object's data.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what self is and how Python fills it in when a method is called
  2. Write methods that read and change the instance's own data
  3. Spot the missing self behind "takes 1 positional argument but 2 were given"

In practice

A few lines that show Methods and self doing its job.

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

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

acct = Account(100)
print(acct.withdraw(30))       # 70

The common mistake

Watch for

Leaving self out of the parameter list. Calling acct.withdraw(30) then fails with "takes 1 positional argument but 2 were given", because Python passes the instance first.

What to know first

Your roadmap puts these before Methods and self, unless you already know them.

How it stays learned

Once a session shows you understand Methods and self, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Methods and self.

Previous in the module← Classes and instances
Next in the moduleInheritance →