Course contentsShow
← Python
Lesson 414 of 1,0607. Object-Oriented ProgrammingFree lesson

Defining Instance Methods for Behavior

Learners will create functions inside classes that define the specific actions or behaviors that objects can perform on their data.

In this lesson, you will learn how to breathe life into your objects by defining instance methods to create dynamic behaviors.

Up until now, you have used classes as blueprints to store data in instance variables. However, a static collection of data is rarely enough. In real-world applications, objects need to do things with the information they hold. We accomplish this by defining instance methods inside our class.

Adding Action to Your Objects

An instance method is simply a function defined inside a class. Just like the __init__ constructor, these methods take self as their first parameter. This self keyword is the "magic bridge" that allows the method to access the specific instance variables of the object it is acting upon.

Think of an object as a smart container: the instance variables are the "ingredients," and the instance methods are the "recipes" that tell the object how to transform or use those ingredients.

Consider this BankAccount class:

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

    # This is an instance method
    def deposit(self, amount):
        self.balance += amount
        print(f"{self.owner} deposited {amount}. New balance: {self.balance}")

# Usage
my_account = BankAccount("Alice", 100)
my_account.deposit(50)

Why Use Instance Methods?

When you 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 that exact object. This allows you to create as many accounts as you want, and each one will update its own unique balance without interfering with the others.

By grouping these behaviors inside the class, your code becomes much easier to maintain. Instead of writing external functions that guess how to modify your data, you provide the object with the built-in capability to manage its own state.

Key Takeaway: Instance methods allow objects to perform actions on their own internal data by using the self parameter to access specific instance variables.