Lesson 5 of 15 · Behaviour
Methods
Learn how Python instance methods read and change an object's data, call other methods, return values and chain together, with clear definitions and examples.
- 7 min read
- Intermediate
- Reviewed
- What an instance method is and what state means
- How methods read and change an object's data
- How one method can use another
- Why returning a value is usually better than printing it
- How to chain method calls together
Methods are an object's actions
You have already written a few methods. In this lesson you will learn to use them well.
Almost every method you write will be an instance method. (In the next lesson you will meet two other kinds.)
An object's state
A bank account's state is its owner and its balance right now. When you deposit money, the state changes. Methods are how you look at the state and how you change it.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount): # changes the state
self.balance += amount
def withdraw(self, amount): # changes the state, with a check
if amount > self.balance:
print("Not enough money")
return
self.balance -= amount
def summary(self): # reads the state
return f"{self.owner} has {self.balance}"
account = BankAccount("Ada", 100)
account.deposit(50)
account.withdraw(500)
account.withdraw(30)
print(account.summary())Each method has one clear job. Code outside the class never touches balance directly. It just asks the account to deposit or withdraw, and the account looks after its own rules.
Methods with parameters
A method can take any number of extra parameters after self. Call it with only those. Python passes self for you.
class Thermostat:
def __init__(self, temperature):
self.temperature = temperature
def change_by(self, degrees):
self.temperature += degrees
def set_between(self, low, high):
if self.temperature < low:
self.temperature = low
elif self.temperature > high:
self.temperature = high
room = Thermostat(30)
room.change_by(-5)
print(room.temperature)
room.set_between(18, 22)
print(room.temperature)room.set_between(18, 22) passes 18 as low and 22 as high. Default values and keyword arguments work too, just as in normal functions.
Methods that use other methods
Inside a class, a method can call another method of the same object with self.method_name(). This keeps each method small and avoids writing the same code twice.
class Order:
def __init__(self, prices):
self.prices = prices
def subtotal(self):
return sum(self.prices)
def tax(self):
return self.subtotal() * 0.18
def total(self):
return self.subtotal() + self.tax()
order = Order([100, 250, 50])
print(order.subtotal())
print(order.tax())
print(order.total())total() does not repeat the adding-up. It reuses subtotal() and tax(). If the tax rule ever changes, you change it in one place.
Return a value, do not just print it
A method that prints shows text on the screen, and that is all. A method that returns gives back a value that the rest of your program can store, compare, add up or print, whatever it needs.
class Circle:
def __init__(self, radius):
self.radius = radius
def print_area(self): # can only show the result
print(3.14159 * self.radius ** 2)
def area(self): # gives the result back
return 3.14159 * self.radius ** 2
small = Circle(1)
big = Circle(3)
total = small.area() + big.area() # only possible because area() returns
print(round(total, 2))
result = small.print_area()
print(result)print_area() displays the number, but hands back nothing, so result is None. You cannot add None to anything. Prefer methods that return, and print the result outside the class when you need to see it.
Method chaining
If a method that changes the object ends with return self, you can call another method straight away on the result.
class Message:
def __init__(self, text):
self.text = text
def shout(self):
self.text = self.text.upper()
return self
def add_emphasis(self, mark="!"):
self.text = self.text + mark * 3
return self
note = Message("good morning")
note.shout().add_emphasis()
print(note.text)note.shout() changes the text and returns note itself, so .add_emphasis() then runs on note too. You will see this style in data and AI libraries, where you set several options in one line.
Common mistakes
Build a shopping cart that remembers its items and can count them and add up the price.
# Write a class called ShoppingCart.
# - __init__ starts with an empty list self.items
# - add_item(self, name, price, quantity=1) appends (name, price, quantity) to self.items
# - item_count(self) returns the total quantity of all items
# - total(self) returns the total price (price * quantity for each item)
cart = ShoppingCart()
cart.add_item("Notebook", 60, 3)
cart.add_item("Pen", 15)
cart.add_item("Bag", 900)
print("Items:", cart.item_count())
print("Total:", cart.total())
# Output must be exactly:
# Items: 5
# Total: 1095
Inside a class, how does the total() method correctly call the subtotal() method of the same object?
Summary
- An instance method works on one object and receives it as
self. - An object's state is its current data. Methods read and change it.
- Methods can take extra parameters and can call each other with
self.method(). - Prefer returning values over printing them, so the rest of the program can use the result.
- Ending a changing method with
return selfallows method chaining.
Next: methods that belong to the class itself, and methods that need no object at all.
Finished reading? Tick it off to track your progress.