📦 Objects & Classes

Bundle data and behavior together

← Back to Architecture

🧸 Think of a blueprint

A class is a blueprint. An object is a thing built from that blueprint. One "Dog" blueprint can make many dogs — each with its own name, but all able to bark.

This idea is called Object-Oriented Programming (OOP). It lets you bundle data (a dog's name) and behavior (barking) into one neat package.

🏗️ Defining a class

class Dog: def __init__(self, name): self.name = name # data (attribute) def bark(self): # behavior (method) return self.name + " says Woof!" rex = Dog("Rex") # make an object print(rex.bark()) # Rex says Woof!

💡 Decoding the pieces

  • __init__ is the constructor — it runs when you create an object.
  • self means "this particular object."
  • Attributes are variables on the object; methods are its functions.

🔐 Encapsulation

An object keeps its data inside and lets you change it through methods. This protects the data from invalid changes.

class BankAccount: def __init__(self): self.balance = 0 def deposit(self, amount): if amount > 0: self.balance += amount

🧬 Inheritance

A class can inherit from another, reusing its code and adding more. A Puppy is a Dog that can also play.

class Puppy(Dog): def play(self): return self.name + " wags its tail!" buddy = Puppy("Buddy") print(buddy.bark()) # inherited from Dog print(buddy.play()) # new ability

✅ What you learned

  • A class is a blueprint; an object is built from it.
  • __init__ sets up attributes; self is "this object."
  • Methods are behaviors; attributes are data.
  • Inheritance lets one class reuse and extend another.