Skip to content

Defining and Using Instance Methods in Python Classes

Updated: at 05:01 AM

Instance methods are an essential concept in object-oriented programming that allow objects to have associated functions. In Python, instance methods are defined inside a class and belong to class instances rather than the class itself.

This guide will provide a detailed overview of instance methods in Python, including:

Table of Contents

Open Table of Contents

What are Instance Methods?

In object-oriented programming, classes allow us to create objects which are instances of that class. Objects created from a class have access to attributes and behaviors defined in the class.

Instance methods are functions defined inside a class that belong to the objects (instances) of that class. They operate on the instance itself, having direct access to the object’s attributes and state.

For example:

class Person:

  def __init__(self, name, age):
    self.name = name
    self.age = age

  def celebrate_birthday(self):
    print(f"Happy Birthday {self.name}!")
    self.age += 1

p1 = Person("Alice", 25)
p1.celebrate_birthday()
# Outputs "Happy Birthday Alice!"

print(p1.age)
# Prints 26

Here celebrate_birthday() is an instance method that operates on the Person instance p1 to update its state. This is only possible because instance methods can access the object’s attributes like self.name and self.age.

Instance methods provide a way to attach reusable behaviors to class instances. All objects created from the same class will have access to those methods.

Difference Between Instance Methods and Other Methods

It’s important to distinguish instance methods from other types of methods in Python:

So regular instance methods are the only ones with access to the object instance via self, allowing them to operate on instance attributes.

Syntax for Defining an Instance Method

The syntax for defining an instance method in a Python class is:

class MyClass:

  def instance_method(self, other_parameters):

    # Method body

We define instance methods the same as normal functions, except they take self as the first parameter.

The self parameter does not need to be named self - technically any name can be used, but self is universally followed as the convention.

Inside the method definition, we can access instance-specific information via self:

class BankAccount:

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

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

Here self.balance allows the deposit() method to modify state on the BankAccount instance.

The Self Parameter

The self parameter in instance methods refers to the instance itself, allowing access to the object’s attributes and methods.

When calling a method on an instance:

my_account = BankAccount(500)
my_account.deposit(100)

Python automatically passes my_account as the self argument to deposit(), binding it to the instance.

Inside deposit(), we can then use self to read or modify attributes on my_account:

class BankAccount:

  def deposit(self, amount):
    self.balance += amount # Modifies my_account's balance

This is essential behavior for instance methods to operate on instance state.

Some key notes on self:

So self enables instance methods to directly manipulate their instance, while regular functions cannot. This encapsulation is a key advantage of object-oriented design.

Calling Instance Methods on Objects

To call an instance method, we simply call it on an instance of the class:

class Person:

  def __init__(self, name):
    self.name = name

  def say_hello(self):
    print(f"Hello, my name is {self.name}")

p1 = Person("Alice")
p1.say_hello()
# Prints "Hello, my name is Alice"

This allows each Person instance to have its own personalized behaviors.

We can call methods on any instance attributes as well:

class ShoppingCart:

  def __init__(self):
    self.items = []

  def add_item(self, item):
    self.items.append(item)

cart = ShoppingCart()
cart.add_item("Apples")

print(cart.items)
# ['Apples']

So instance methods provide reusable behaviors that each object instance can utilize.

Types of Instance Methods

There are a few common conventions for instance methods in Python:

Accessor Methods

Getter methods that simply return (access) attribute values:

class Person:

  def __init__(self, name):
    self.name = name

  def get_name(self):
    return self.name

p = Person("Alice")
print(p.get_name()) # "Alice"

By convention, accessor methods are named get_attribute().

Mutator Methods

Setter methods that modify (mutate) attribute values:

class Person:

  def __init__(self, name):
    self.name = name

  def set_name(self, new_name):
    self.name = new_name

p = Person("Alice")
p.set_name("Bob")
print(p.name) # "Bob"

Mutator methods are named set_attribute().

Utility Methods

Instance methods that perform useful operations on the object, but don’t directly get or set attributes:

import math

class Circle:

  def __init__(self, radius):
    self.radius = radius

  def area(self):
    return math.pi * (self.radius ** 2)

  def circumference(self):
    return 2 * math.pi * self.radius

c = Circle(5)
print(c.area()) # 78.53981633974483
print(c.circumference()) # 31.41592653589793

Utility methods implement reusable behaviors related to the class.

Instance Methods vs. Class and Static Methods

A key distinction in Python is between instance, class and static methods:

For example:

class Calculator:

  def __init__(self, num1, num2):
    self.num1 = num1
    self.num2 = num2

  def add(self): # Instance method
    return self.num1 + self.num2

  @classmethod
  def double_add(cls, num1, num2): # Class method
    return cls(num1, num2).add() * 2

  @staticmethod
  def valid_pair(num1, num2): # Static method
    return isinstance(num1, (int, float)) and isinstance(num2, (int, float))

calc = Calculator(2, 3)

calc.add()         # 5
Calculator.double_add(2, 3) # 10
Calculator.valid_pair(2, "3") # False

So instance methods are specifically used when we want a function that belongs to and can access individual objects created from a class.

Example Use Cases for Instance Methods

Here are some common use cases where instance methods are useful in Python:

Encapsulating object behavior

class GameCharacter:

  def __init__(self, name, level):
    self.name = name
    self.level = level

  def attack(self, target):
    # Logic to damage target based on character stats

Providing object-specific actions

class BankAccount:

  def deposit(self, amount):
    # Add amount to account balance

  def withdraw(self, amount):
    # Remove amount from balance if sufficient funds

Implementing behaviors related to object data

class Invoice:

  def get_due_date(self):
    return self.date + datetime.timedelta(days=30)

  def add_line_item(self, product, price):
    self.items.append(...)

Creating utility methods

import math

class Circle:

  def area(self):
    return math.pi * (self.radius ** 2)

Best Practices for Instance Methods

Here are some best practices to keep in mind when defining instance methods in Python:

Using properly structured instance methods makes class design more intuitive and encapsulated.

Conclusion

Instance methods are a key way to incorporate reusable logic into class objects in Python. Defining them with self allows accessing and manipulating the object’s attributes and state.

Understanding instance methods is essential for mastering object-oriented programming and design in Python. Used properly, they encapsulate object behavior and data as first-class operations tied to classes.

In this guide we covered:

With this knowledge you are now ready to leverage instance methods effectively within your Python classes to create more powerful and reusable object-oriented code.