Grade 10 Computer Science · Objects

An operation with a subject

Why a method differs from an ordinary function, and what that means for writing.

Two parameters in the definition, one in the call

The operation’s definition lists two parameters, and the call passes only one value. Python does not complain, and everything works. Where did the second parameter go, and who passes it without being asked?

An operation written inside a class is called a method, and its difference from an ordinary function is not syntactic. An ordinary function has only arguments; a method has a subject — the object it acts on — and only then arguments. That subject is always available to it, which is why it need not receive the data in parameters.

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

    def step(self, amount=1):
        self.value += amount
        return self.value

c = Counter()
c.step()      # 1  — c is passed as self
c.step(5)     # 6  — 5 is passed as amount

What a method returns and what it changes

A method can do one of two things, and sometimes both: return an answer based on the state, or change the state. It is worth deciding in advance which it is, and writing the name accordingly. A name that is a noun — average, total, size — promises a question with no side effects. A name that is a verb — add, reset, save — promises a change. When the name and the deed disagree, everyone reading the code is misled, and that is a mistake hard to find because the code itself is correct.

Kind of methodThe fitting nameWhat is promised
A questionA nounChanges nothing
An actionA verbChanges the state

Example 1 — why the call looks short

  1. The definition has two parameters.
  2. The call shows only one.
  3. The object is passed automatically as the first.

Example 2 — a name that promises correctly

  1. A method named average changes nothing.
  2. A method named add changes the state.
  3. The reader knows what to expect without reading.
The call looks short, because the object before the dot is the first parameter.