Legends ofPythos
Claim your name
Objects and Classes

Methods: giving objects behaviour

Lesson 4 of 13

Watch the lesson1:21 · 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)

print(f"{tom.owner}: {tom.balance}")   # Tom: 120.0
print(f"{sara.owner}: {sara.balance}" )# Sara: 45.0
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 math, 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, increment it three times, and print its final count.
c = None

Run your code to check it against the tests.

Exercise 2

+35 XP
Create a class Rectangle with width and height set in __init__.
Add two methods:
  1. area() – returns the area (width * height)
  2. is_square() – returns True if it's a square, False otherwise
Then create a 4x6 rectangle, print its area, then print whether it is a square.
r = None

Run your code to check it against the tests.

Exercise 3

+35 XP
Create a class Task with attributes: title (string), done (boolean, starts False).
Add three methods:
  1. complete() – sets done to True
  2. status_message() – returns 'Done' if completed else 'Pending'
  3. summary() – calls status_message() internally and returns an f-string like '{title}: {status}'
Create a task titled 'Write report', complete it, then print its summary.
t = None

Run your code to check it against the tests.