Lesson 9 of 12
Learn object-oriented programming with flowchart blocks: objects with fields, classes as templates, and methods. Open working examples and see the code.
About 7 minutes · 2 parts, each with a program to try
Part 1 of 2
An object is one value with named parts, called fields: a pet with a name and an energy. Read one with a dot: pet.energy.
Change a Field updates one part: pet.energy = pet.energy + 1.
from types import SimpleNamespace
pet = SimpleNamespace(name="Tom", kind="cat", energy=3)print("Meet " + pet.name + " the " + pet.kind + ", with energy " + str(pet.energy))snacks = int(input("How many snacks? "))for _ in range(snacks): pet.energy = pet.energy + 2print(pet.name + " now has energy " + str(pet.energy) + " ⚡")Part 2 of 2
A Class describes what every object of that kind has. Pet("Tom") makes a new Pet called Tom.
A method is a function that belongs to the class, and runs on one object: account.deposit(100).
class Account: def __init__(self, owner="", balance=0): self.owner = owner self.balance = balance
def deposit(self, amount): self.balance = self.balance + amount
def withdraw(self, amount): if amount <= self.balance: self.balance = self.balance - amount else: print("Sorry " + self.owner + ", there's only ₹" + str(self.balance) + " in your account.")
asha = Account("Asha", 100)ravi = Account("Ravi")asha.deposit(50)ravi.deposit(20)asha.withdraw(500)ravi.withdraw(5)print(asha.owner + ": ₹" + str(asha.balance))print(ravi.owner + ": ₹" + str(ravi.balance))Quick check