Learn / Python / Classes and Objects

Intermediate 18 min

Classes and Objects

Model data with classes, __init__, methods, and self.

What you will learn

  • Define a class with __init__
  • Add instance methods
  • Understand self
python
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

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

acct = BankAccount("Amar", 100)
acct.deposit(50)
print(acct.balance)

Try it yourself

Add a withdraw method that refuses negative balances.