Legends ofPythos
Claim your name
Objects and Classes

Methods: giving objects behaviour

Lesson 4 of 13

Watch the lesson5:30 · with Torsten

What is a method?

Think of an object as a person in a restaurant: they have data (their order) and behaviour (how to pay). A method is the action part. It lets your class do something instead of just sitting there holding values.
class CoffeeOrder:
    def __init__(self, drink):
        self.drink = drink
        self.size = 'medium'

    def add_syrup(self):
        print(f'Adding syrup to {self.drink}')

order = CoffeeOrder('latte')
order.add_syrup()
A method inside a class
add_syrup is a method. It lives inside the class and knows about self. You call it on a specific object, and it works with that order's own data.

The self parameter

Every method starts with self. This word means this specific instance. When two objects of the same class exist, each has its own data. self is how the code knows whose data to touch.
class BankAccount:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0.0

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

tom = BankAccount('Tom')
sara = BankAccount('Sara')

tom.deposit(120)
sara.deposit(45)

# Prints Tom: 120.0, then Sara: 45.0
print(f"{tom.owner}: {tom.balance}")
print(f"{sara.owner}: {sara.balance}")
Two separate accounts
deposit changes self.balance. Because each account has its own storage, depositing to one does not affect the other.

Methods that return values

class Invoice:
    def __init__(self, item, price):
        self.item = item
        self.price = price

    def apply_discount(self, percent):
        discount = self.price * (percent / 100)
        return self.price - discount

bill = Invoice('notebook', 25.00)
cost = bill.apply_discount(10)
print(cost)   # 22.5
Reading data and returning a result
apply_discount reads self.price, does the maths, and returns a new number. The original object is unchanged unless you explicitly assign to an attribute.

Changing state inside methods

class Task:
    def __init__(self, title):
        self.title = title
        self.done = False

    def complete(self):
        self.done = True

task = Task('write report')
print(task.done)   # False
task.complete()
print(task.done)   # True
Updating attributes
complete() flips self.done. This is how objects remember state over time. Your exercises will use this pattern: methods that read, calculate, or update the data stored on each instance.

Your turn

0 of 3 solved

Exercise 1

+35 XP
Create a class called Counter. It should start with an attribute count set to zero.
Add two methods:
  1. increment() – increases the count by one and returns nothing
  2. get_count() – returns the current value of count
Then create a counter named c, increment it three times, and print what c.get_count() returns. Print nothing else.
c = None

Run your code to check it against the tests.

Exercise 2

+35 XP
Create a class Rectangle whose __init__ takes a width and a height and stores them as self.width and self.height.
Add two methods:
  1. area() – returns the area (width times height)
  2. is_square() – returns True if it's a square, False otherwise
Then create a 4 by 6 rectangle, print what its area() returns, then print what its is_square() returns. Print nothing else.
r = None

Run your code to check it against the tests.

Exercise 3

+35 XP
Create a class Task whose __init__ takes a title and stores it as self.title, and sets self.done to False.
Add three methods:
  1. complete() – sets self.done to True
  2. status_message() – returns 'Done' if the task is done, and 'Pending' if not
  3. summary() – stores what self.status_message() returns in status, then returns f'{self.title}: {status}'
Create a task titled 'Write report', complete it, then print what its summary() returns. Print nothing else.
t = None

Run your code to check it against the tests.