Methods

Give your objects the ability to do things.

Introduction

So far, your objects can store data through attributes. But objects in the real world do not just have things -- they also do things. A dog barks. A car accelerates. A bank account processes deposits. These actions are called methods.

What is a Method?

A method is simply a function that is defined inside a class. It defines what an object can do.

Attributes = What an object HAS

name, age, color, speed, balance

Methods = What an object DOES

bark(), drive(), deposit(), calculate()

Your First Method

class Dog:
    name = "Buddy"

    def bark(self):
        print(f"{self.name} says: Woof!")

dog1 = Dog()
dog1.bark()  # Buddy says: Woof!

Notice two important things: the method is defined inside the class (indented under it), and it takes self as its first parameter.

What is self?

self refers to the current object -- the specific object that is calling the method. It is how the method knows which object's data to work with.

class Dog:
    name = "Unknown"

    def bark(self):
        print(f"{self.name} says: Woof!")

dog1 = Dog()
dog1.name = "Buddy"

dog2 = Dog()
dog2.name = "Max"

dog1.bark()  # Buddy says: Woof!
dog2.bark()  # Max says: Woof!

Key rule: self must always be the first parameter in any method. When you call dog1.bark(), Python automatically passes dog1 as self. You never pass it yourself.

Methods with Parameters

Methods can accept additional parameters beyond self, just like regular functions:

class Calculator:
    def add(self, a, b):
        return a + b

    def multiply(self, a, b):
        return a * b

calc = Calculator()
print(calc.add(5, 3))       # 8
print(calc.multiply(4, 7))  # 28

A More Complete Example

Here is a class that combines attributes and methods in a meaningful way:

class BankAccount:
    balance = 0

    def deposit(self, amount):
        self.balance += amount
        print(f"Deposited ${amount}. Balance: ${self.balance}")

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print(f"Withdrew ${amount}. Balance: ${self.balance}")
        else:
            print("Insufficient funds.")

acc = BankAccount()
acc.deposit(500)     # Deposited $500. Balance: $500
acc.withdraw(200)    # Withdrew $200. Balance: $300
acc.withdraw(400)    # Insufficient funds.

Notice how methods can access and modify the object's attributes using self. The deposit method increases the balance, and the withdraw method checks if there are sufficient funds before reducing it.

OOP Terms

  • Method: A function defined inside a class. It defines what an object can do.
  • self: A reference to the current object. It lets the method access that specific object's attributes and other methods.

Best Practices

  • Always include self as the first parameter in every method.
  • Use descriptive verb names for methods: deposit(), calculate_gpa(), send_message().
  • Keep methods focused -- each method should do one thing well.

Common Mistakes

  • Forgetting self as the first parameter -- this causes a TypeError.
  • Writing name instead of self.name inside a method -- the method cannot find the attribute without self.
  • Passing self when calling a method: dog1.bark(dog1) is wrong. Just use dog1.bark().

Practice Exercises

  1. Create a Greeter class with a name attribute and a greet() method that prints "Hello, my name is [name]!".
  2. Create a Rectangle class with width and height attributes and an area() method that returns width times height.
  3. Extend the BankAccount example by adding a check_balance() method that simply prints the current balance.

Summary

  • Methods are functions defined inside a class -- they define what objects can do.
  • self is always the first parameter and refers to the current object.
  • Methods can accept additional parameters and return values, just like regular functions.
  • Use self.attribute inside methods to access the object's data.