In this lesson, you will learn how to define and access instance methods to give your objects the ability to perform actions using their own internal data.
Bringing Objects to Life
Up until now, you have used classes to store data as attributes. However, an object becomes truly powerful when it can "do" something with that data. We achieve this by defining instance methods—functions that live inside a class and have direct access to a specific object's attributes.
To define an instance method, you write a function inside your class and always include self as the first parameter. The self parameter acts as a bridge, allowing the method to reach inside the specific instance it is called upon to read or change its data.
A Concrete Example
Imagine we are building a simple BankAccount class. We want an instance method that allows us to deposit money and update the account balance:
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
# We use 'self' to access the object's current balance
self.balance += amount
print(f"{self.owner} deposited ${amount}. New balance: ${self.balance}")
# Creating an instance
my_account = BankAccount("Alice", 100)
# Accessing the instance method
my_account.deposit(50)
In the code above, deposit is an instance method. When we call my_account.deposit(50), Python automatically passes my_account into the self parameter. Inside the method, self.balance refers specifically to the balance of the my_account object. If you had another object called friend_account, calling deposit on it would update that object's balance instead, because self would point to the new instance.
Why It Matters
By using self within instance methods, you ensure that your code is modular. You don't need to manually pass data into every function; the object carries its own context with it. This allows you to encapsulate behavior, keeping your logic tied directly to the data it manages.
Key Takeaway: Instance methods use the self parameter to interact with and modify the specific attributes of the object they were called upon.