CodeMIRAI
0 XP

Methods

2 min read 4 runnable examples Quiz included

Methods are functions defined inside a class. They give objects behaviour, and they work on the object's own data through self.

Python
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

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

    def withdraw(self, amount):
        if amount > self.balance:
            print(f"Declined: {self.owner} only has {self.balance}")
            return
        self.balance -= amount

acct = BankAccount("Mei", 100)
acct.deposit(50)
acct.withdraw(500)
acct.withdraw(30)
print(acct.balance)

Methods that return values

Python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

    def is_square(self):
        return self.width == self.height

r = Rectangle(4, 6)
print(r.area(), r.perimeter(), r.is_square())
print(Rectangle(5, 5).is_square())

Methods calling methods

Inside a class, call another method with self.method():

Python
class Cart:
    def __init__(self):
        self.items = []          # a fresh list for each cart

    def add(self, name, price, qty=1):
        self.items.append((name, price, qty))

    def subtotal(self):
        return sum(price * qty for _, price, qty in self.items)

    def total(self, tax=0.18):
        return round(self.subtotal() * (1 + tax), 2)

    def receipt(self):
        for name, price, qty in self.items:
            print(f"{name:<12} {qty} x {price:>7.2f}")
        print(f"{'Total':<12} {self.total():>11.2f}")

cart = Cart()
cart.add("Keyboard", 89.99)
cart.add("Mouse", 24.50, qty=2)
cart.receipt()

Objects working together

Objects can hold other objects and call their methods:

Python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
        self.available = True

class Library:
    def __init__(self):
        self.books = []

    def add(self, book):
        self.books.append(book)

    def borrow(self, title):
        for book in self.books:
            if book.title == title and book.available:
                book.available = False
                return f"You borrowed {title}."
        return f"Sorry, {title} isn't available."

lib = Library()
lib.add(Book("Clean Code", "Robert C. Martin"))
print(lib.borrow("Clean Code"))
print(lib.borrow("Clean Code"))
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.