Python 3D Academyবাংলা

Methods that change an object

🌍 In real life. A tally counter at a cricket gate clicks up by one for each person who comes in. Each gate has its own counter: clicking at Gate A doesn't change Gate B. Objects work the same way:

  • a method can change its object's attributes: self.count = self.count + 1
  • each object keeps its own values
  • so calling a method on one object leaves the others alone

The idea in one sentence: a method can change its own object's attributes through self, so each object keeps its own state, and the methods are the safe way to change it.

Its words:

  • state: the current values of an object's attributes, like a balance
  • changing the object: self.count = self.count + 1 inside a method
  • guard: a check in a method that refuses a bad change by raising an error

Step by step, for gate_a.click():

  1. Python runs click with self = gate_a.
  2. self.count = self.count + 1 reads gate A's count and writes the new one back onto gate A.
  3. Gate B's count isn't touched: it's a different object.

A bank account is the classic example. The balance should only change through deposit and withdraw. withdraw refuses (raises a ValueError, Chapter 18) when there isn't enough money, so the balance can never go wrong:

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

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

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("not enough money")
        self.balance = self.balance - amount

acc = Account("Ana", 50)
acc.deposit(20)
acc.withdraw(30)
print(acc.balance)
try:
    acc.withdraw(500)
except ValueError as e:
    print("Refused:", e)
print(acc.balance)

Remember Chapter 13: a name points to an object. Two names can point to the same object, like two people holding keys to the same locker. A change made through one key shows up for the other. Here Account(…) is called only once, so there is only one account:

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

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

mine = Account("Ana", 50)
also_mine = mine
also_mine.deposit(25)
print(mine.balance)
print(mine is also_mine)

Mistakes and edge cases.

  • Forgetting self. on the left. balance = self.balance + n inside deposit makes a local variable and throws it away; the account's balance doesn't change, and there's no error.
  • Changing the attribute from outside. acc.balance = -500 skips the guard in withdraw; use the methods.
  • Two names, one object. b = a then b.deposit(5) changes the one account both names point to (above).
  • Returning instead of storing. A method that only returns the new balance leaves the object unchanged unless it also sets self.balance.

Quiz

  1. What does this print?

    class Counter:
        def __init__(self):
            self.count = 0
    
        def increment(self):
            self.count = self.count + 1
    
    c = Counter()
    c.increment()
    c.increment()
    c.increment()
    print(c.count)
  2. What does this print?

    class Counter:
        def __init__(self):
            self.count = 0
    
        def increment(self):
            self.count = self.count + 1
    
    a = Counter()
    b = Counter()
    a.increment()
    print(a.count, b.count)
  3. What does this print?

    class Box:
        def __init__(self):
            self.items = []
    
        def add(self, item):
            self.items.append(item)
    
    x = Box()
    y = x
    y.add("pen")
    print(x.items)
  4. Why can withdraw raise a ValueError instead of returning a message?

    • So the caller can't miss the problem, and the balance never goes wrong
    • Methods can't return strings
    • raise is faster
  5. Which line has a mistake?

    class Counter:
        def __init__(self):
            self.count = 0
    
        def increment(self):
            count = self.count + 1

Coding tasks

  1. Write a class Counter whose objects start with count 0 and have a method increment() that adds 1.

  2. Write a class Account with a balance, a method deposit(amount), and a method withdraw(amount) that raises a ValueError if the amount is more than the balance.

  3. Write a class Playlist whose objects start with an empty list songs, with a method add(song) that appends to it. Each playlist needs its own list.