Hone

Lessons · Python · methods and attributes

Methods are functions that receive the object

A method is a function defined inside the class. Calling d.bark() runs bark with self = d, so it can read and change that object's data.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

deposit, withdraw, move, render, send: the actions a thing can do belong next to its data. A method that changes self.count changes the real object, and the change is still there on the next call.

How to think about it

Ask: does this action need the object's own data? Then it is a method, with self first. Read attributes without parentheses (d.name); call methods with them (d.bark()).

Worked example

class Counter:
    def __init__(self):
        self.count = 0
State the object carries.
    def tick(self):
self is the object the method was called on.
        self.count += 1
Changes the real object, not a copy.
        return self.count
c = Counter()
c.tick(); c.tick()
Two calls on the same object.
print(c.count)
2: the change persisted.

Your turn

Write the method that adds to the balance.

class Account:
    def __init__(self, balance):
        self.balance = balance
    def deposit(, amount):
        self.balance += amount

The trap

Forgetting the parentheses: c.tick reads the method as a value and never runs it. Nothing changes and there is no error.

Next in Python

Every Python lesson on one page

Practise methods and attributes on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.