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
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)Account. Its methods are stored, but none of them run yet.class Account belongs to it.deposit is stored in Account. It runs only when it is called on an object.Account is now defined, ready to make objects from.self is the new object. self.owner = owner stores the name on this object.balance with the value 50 is added to the Account that self points to.owner with the value 'Ben' is added to the Account that self points to.balance with the value 0 is added to the Account that self points to.balance in the Account that mine and self point to changes from 50 to 75.deposit(), with self = {owner: 'Ben', balance: 0} and amount = 10. It gets its own names.balance in the Account that yours and self point to changes from 0 to 10.self.balance.deposit() has finished, so its names are gone.Answer: mine. The object before the dot.
Answer: Every time an object is created. Account(...) triggers it.
← lambda, map, filter and sorted · Inheritance and super() →