Methods
After this: Write deposit and withdraw as methods, follow self (this) in a trace, and give an object its own printed text.
On this page · 7 sections · 4 checks
A till in a shop has buttons: add an item, print the receipt. Each button works on the till it is part of. Pressing "add an item" on till 3 never changes till 5. The actions of a class are buttons of that kind: written once, and each works on the object it was pressed on.
A function that belongs to the object
A is a function written inside a class. You call it on an object with a dot, as in a.deposit(50), and inside it can read and change the fields of that object. The constructor from lesson 2 is a method too: the one that runs when an object is made.
How does deposit know which account to change? Through its first box. In Python the first parameter of every method is self, and when you write a.deposit(50), Python puts a into self and 50 into amount.In Java that box is named this, and you do not write it as a parameter: a.deposit(50) puts a into this and 50 into amount all the same. The line inside, self.balance = self.balance + amountbalance = balance + amount;, reads the balance of that object, adds the amount, and stores the sum back in the same field.
Work through a.deposit(50), with a holding Ana's account and 100:
- The call opens a frame named
deposit. Its first box, selfthis, holds Ana's account, andamountholds 50. - The line inside reads the balance, 100, adds 50, and stores 150 in the field. The band shows selfthis change to Account(name='Ana', balance=150)Account(name="Ana", balance=150).
- The method returns nothing and the frame closes. Back in the program,
ashows the new balance:aand selfthis were the same object all along.
The task below calls deposit twice, on two different accounts. Watch the first box of the frame each time.
- Run the programRun it and step through. Each deposit call opens a frame named deposit. Read its first box, self (this in Java): it is the account the call was made on. Compare the two calls.
class Account: def __init__(self, name, balance): self.name = name self.balance = balance
def deposit(self, amount): self.balance = self.balance + amount
a = Account("Ana", 100)b = Account("Ben", 10)a.deposit(50)b.deposit(5)print(a.balance, b.balance)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
A method that answers
withdraw has a rule: if the amount asked for is more than the balance, refuse. A method can return a value like any function. This one returns Truetrue when the money was taken and Falsefalse when it refused. Ben has 10 and asks for 500.
class Account: def __init__(self, name, balance): self.name = name self.balance = balance
def withdraw(self, amount): if amount > self.balance: return False self.balance = self.balance - amount return True
b = Account("Ben", 10)print(b.withdraw(500))print(b.balance)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The condition amount > self.balanceamount > balance compares 500 with 10. It is true, so the method returns Falsefalse at once. The line that changes the balance never runs, and Ben still has 10.
The whole class
Here is Account with both methods, and the example this tutorial is built on: Ana deposits 50 and withdraws 30; Ben asks for 500.
class Account: def __init__(self, name, balance): self.name = name self.balance = balance
def deposit(self, amount): self.balance = self.balance + amount
def withdraw(self, amount): if amount > self.balance: return False self.balance = self.balance - amount return True
a = Account("Ana", 100)a.deposit(50)a.withdraw(30)print(a.balance)b = Account("Ben", 10)print(b.withdraw(500))print(b.balance)120 False 10
class Account { String name; int balance;
Account(String name, int balance) { this.name = name; this.balance = balance; }
void deposit(int amount) { balance = balance + amount; }
boolean withdraw(int amount) { if (amount > balance) { return false; } balance = balance - amount; return true; }}
public class Main { public static void main(String[] args) { Account a = new Account("Ana", 100); a.deposit(50); a.withdraw(30); System.out.println(a.balance); Account b = new Account("Ben", 10); System.out.println(b.withdraw(500)); System.out.println(b.balance); }}120 false 10
100 plus 50 minus 30 leaves 120. Ben's withdraw is refused, so the print shows Falsefalse, and his balance stays 10.
Run it
Change Ben's 500 to 5 and run again: the withdraw is allowed, and the last two lines change.
Printing an object
What does print(a)System.out.println(a) show? Not the fields. Without help, the program prints a code that only says where the object lives, which tells a reader nothing. The number at the end of that code is an address that can change from run to run, so the band leaves it out.The letters after the @ are a code Java chose for the object. They tell a reader nothing, and the band shows made-up ones.
class Account: def __init__(self, name, balance): self.name = name self.balance = balance
a = Account("Ana", 100)print(a)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
To choose the text yourself, write one more method with a fixed name, __str__toString, that returns the text. Print calls it for you and shows what it returns.
class Account: def __init__(self, name, balance): self.name = name self.balance = balance
def __str__(self): return self.name + ": " + str(self.balance)
a = Account("Ana", 100)print(a)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The trace shows the call: print opens a frame for __str__toString with selfthis holding the account, the method returns Ana: 100, and that is what is printed. str(self.balance) turns the number into text so that it can be joined to the name.Java needs the word public on toString, because every object already has one and yours replaces it.
Check yourself
a holds Ana's account with 100. The program runs a.deposit(50) and then a.withdraw(30). What does a.balance hold now?
b holds Ben's account with 10. The program runs x = b.withdraw(500)boolean x = b.withdraw(500);. What does x hold, and what is b.balance?
Complete the first line of deposit, a method with one input, amount, so that a.deposit(50) works and the program prints 150. Remember the box that comes first in every method.It returns nothing and has no static.
class Account: def __init__(self, name, balance): self.name = name self.balance = balance
____________________ # ← the first line of deposit, with its input amount self.balance = self.balance + amount
a = Account("Ana", 100)a.deposit(50)print(a.balance)class Account { String name; int balance;
Account(String name, int balance) { this.name = name; this.balance = balance; }
____________________ // ← the first line of deposit, with its input amount balance = balance + amount; }}
public class Main { public static void main(String[] args) { Account a = new Account("Ana", 100); a.deposit(50); System.out.println(a.balance); }}Complete the one line inside deposit, so that the amount is added to the balance of the account the method was called on, and the program prints 150.
class Account: def __init__(self, name, balance): self.name = name self.balance = balance
def deposit(self, amount): ____________________ # ← add amount to this account's balance
a = Account("Ana", 100)a.deposit(50)print(a.balance)class Account { String name; int balance;
Account(String name, int balance) { this.name = name; this.balance = balance; }
void deposit(int amount) { ____________________ // ← add amount to this account's balance }}
public class Main { public static void main(String[] args) { Account a = new Account("Ana", 100); a.deposit(50); System.out.println(a.balance); }}Honesty notes
- Write a method: a function inside a class whose first box, self (this in Java), is the object it was called on.
- Say what deposit and withdraw leave in the balance, and what withdraw returns when the amount is too large.
- Read the frame a method call opens in the trace band, and say which object self (this) is at that moment.
- Give an object its own printed text with __str__ in Python or toString in Java.