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 = 0State the object carries.
def tick(self):self is the object the method was called on.
self.count += 1Changes 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 += amountSolve one with the tests running
The trap
Forgetting the parentheses: c.tick reads the method as a value and never runs it. Nothing changes and there is no error.