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 amountWhat 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 method | The fitting name | What is promised |
|---|---|---|
| A question | A noun | Changes nothing |
| An action | A verb | Changes the state |
Example 1 — why the call looks short
- The definition has two parameters.
- The call shows only one.
- The object is passed automatically as the first.
Example 2 — a name that promises correctly
- A method named average changes nothing.
- A method named add changes the state.
- The reader knows what to expect without reading.