logo

Defining Methods

Methods define what objects can do. They're just functions defined inside a class.

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

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

    def withdraw(self, amount):
        self.balance -= amount

Each method takes self as its first parameter, giving it access to the object's data.

Use the methods on an object:

account = BankAccount(100)
account.deposit(50)
print(account.balance)  # 150

Methods encapsulate behavior with data. The account knows its balance and how to modify it safely.

For method design patterns, see my Python OOP course.