Methods: What Objects Can Do

Adding methods

A method is a function that lives inside a class. It can use and change the object's attributes through self.

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

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

    def withdraw(self, amount):
        if amount > self.balance:
            print("Not enough money!")
        else:
            self.balance -= amount

account = BankAccount("Asha", 100)
account.deposit(50)
account.withdraw(500)
account.withdraw(30)
print(account.owner, "has", account.balance)

Output

Not enough money!
Asha has 120

The account protects itself: withdraw refuses to take out more than the balance. Keeping the rules inside the class means nobody can forget them.

Printing an object nicely

By default, printing an object shows something ugly like <__main__.BankAccount object at 0x...>. Add a __str__ method to choose what it looks like:

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return f"{self.title} by {self.author} ({self.pages} pages)"

    def is_long(self):
        return self.pages > 300

book = Book("Wings of Fire", "A. P. J. Abdul Kalam", 180)
print(book)
print("Long book?", book.is_long())

Output

Wings of Fire by A. P. J. Abdul Kalam (180 pages)
Long book? False

Objects in a list

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

students = [Student("Asha", 91), Student("Ravi", 78), Student("Meena", 85)]
best = students[0]
for student in students:
    if student.marks > best.marks:
        best = student
print("Top student:", best.name)

Output

Top student: Asha

Common mistake: Forgetting self: inside a method write self.balance, not just balance.

HOME LEARN COMMUNITY DASHBOARD