Classes and Objects

A class is a blueprint; objects are made from it, each with its own data. Build two bank accounts and see self in action.

Python · beginner · 8 min · 22 steps · free

What you'll learn

classes.py

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner          # each object gets its own attributes
        self.balance = balance

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

mine = Account("Asha", 50)
yours = Account("Ben")
mine.deposit(25)
yours.deposit(10)
print(mine.owner, mine.balance, yours.owner, yours.balance)

Step by step

  1. Python starts building the class Account. Its methods are stored, but none of them run yet.
  2. Python reads the class body: everything indented under class Account belongs to it.
  3. __init__ runs automatically each time an object is made.
  4. The method deposit is stored in Account. It runs only when it is called on an object.
  5. The class Account is now defined, ready to make objects from.
  6. Account("Asha", 50) makes a new object and calls __init__ on it.
  7. self is the new object. self.owner = owner stores the name on this object.
  8. A new key balance with the value 50 is added to the Account that self points to.
  9. Account("Asha", 50) makes a new object and calls __init__ on it.
  10. A second object, with its own attributes. balance uses its default, 0.
  11. A new key owner with the value 'Ben' is added to the Account that self points to.
  12. A new key balance with the value 0 is added to the Account that self points to.
  13. A second object, with its own attributes. balance uses its default, 0.
  14. mine.deposit(25): inside, self is mine.
  15. balance in the Account that mine and self point to changes from 50 to 75.
  16. Asha's balance: 75.
  17. mine.deposit(25): inside, self is mine.
  18. Python calls deposit(), with self = {owner: 'Ben', balance: 0} and amount = 10. It gets its own names.
  19. balance in the Account that yours and self point to changes from 0 to 10.
  20. The function returns self.balance.
  21. deposit() has finished, so its names are gone.
  22. Two objects from one class, each with separate data. Methods use self to work on the object they were called on.

Common mistakes

Best practices

Key takeaways

Check yourself

What is passed as self in mine.deposit(5)?

Answer: mine. The object before the dot.

When does __init__ run?

Answer: Every time an object is created. Account(...) triggers it.

·

More in Objects, Errors and Generators