Classes and Objects

Back

Loading concept...

🏠 Building Your Own Digital House: Classes and Objects in Python

The Story of the Blueprint

Imagine you want to build a house. Do you start picking up bricks randomly? No! First, you draw a blueprint—a plan that shows exactly how the house should look.

In Python, a class is like a blueprint. An object is the actual house you build from that blueprint.

You can build many houses from one blueprint. Each house is its own thing, but they all follow the same plan!


🎨 Class Definition: Drawing Your Blueprint

A class is how you tell Python: “Here’s my plan for building things.”

The Simplest Blueprint

class Dog:
    pass

That’s it! You just created a blueprint for a Dog. The word class starts your blueprint. Dog is the name. pass means “nothing inside yet.”

A More Useful Blueprint

class Dog:
    species = "Canine"

Now your Dog blueprint says: “All dogs are Canines.”

Think of it like this:

  • 📐 Blueprint = Class
  • 🏠 Actual house = Object
  • ✏️ Drawing the blueprint = Defining the class

🏗️ Object Instantiation: Building From the Blueprint

Having a blueprint is great, but you need actual houses! Instantiation means “create a real thing from the blueprint.”

class Dog:
    species = "Canine"

my_dog = Dog()
your_dog = Dog()

What just happened?

  • Dog() says “build me a dog from the Dog blueprint”
  • my_dog is one real dog
  • your_dog is another real dog
  • Same blueprint, two different dogs!
graph TD A["🎨 Class: Dog Blueprint"] --> B["🐕 my_dog"] A --> C["🐕 your_dog"] A --> D["🐕 neighbor_dog"]

Real Life Example:

  • Cookie cutter = Class
  • Each cookie = Object
  • One cutter makes many cookies!

🎒 Instance Attributes: What Makes Each One Special

Every dog is a dog, but each dog has its own name, own age, own color. These personal details are instance attributes.

class Dog:
    species = "Canine"

my_dog = Dog()
my_dog.name = "Buddy"
my_dog.age = 3

your_dog = Dog()
your_dog.name = "Max"
your_dog.age = 5

What’s happening?

  • my_dog.name = "Buddy" gives THIS dog a name
  • your_dog.name = "Max" gives THAT dog a different name
  • Each dog carries its own information!

Think of twins:

  • Same parents (class)
  • But different names, different favorite foods, different friends
  • Instance attributes = what makes each twin unique

🌍 Class Attributes: What Everyone Shares

Some things are true for ALL dogs, not just one. The species “Canine” applies to every single dog. This is a class attribute.

class Dog:
    species = "Canine"
    legs = 4

buddy = Dog()
max = Dog()

print(buddy.species)  # Canine
print(max.species)    # Canine
print(buddy.legs)     # 4
print(max.legs)       # 4

The Difference:

Class Attributes Instance Attributes
Same for everyone Different for each
Defined in class Given to each object
species = "Canine" buddy.name = "Buddy"
graph TD A["Class: Dog"] --> B["species = Canine"] A --> C["legs = 4"] A --> D["buddy object"] A --> E["max object"] D --> F["name = Buddy"] D --> G["age = 3"] E --> H["name = Max"] E --> I["age = 5"]

🎬 The __init__ Method: The Automatic Setup

Adding attributes one by one is tiring:

dog1 = Dog()
dog1.name = "Buddy"
dog1.age = 3
# So many lines!

Python gives us a magic shortcut called __init__. It runs automatically when you create an object!

class Dog:
    species = "Canine"

    def __init__(self, name, age):
        self.name = name
        self.age = age

Now creating a dog is easy:

buddy = Dog("Buddy", 3)
max = Dog("Max", 5)

print(buddy.name)  # Buddy
print(max.age)     # 5

The magic:

  • __init__ runs immediately when you write Dog("Buddy", 3)
  • It sets up your dog with a name and age right away
  • No extra lines needed!

Think of it like this: When a baby is born, the hospital immediately:

  • Records the name
  • Records the birth date
  • Gives an ID bracelet

__init__ is the hospital—it sets everything up at birth!


🪞 The self Parameter: “I’m Talking About ME”

Look at __init__ again:

def __init__(self, name, age):
    self.name = name
    self.age = age

What is self? It means “this specific object.”

When you write buddy = Dog("Buddy", 3):

  • self becomes buddy
  • self.name = name means buddy.name = "Buddy"

When you write max = Dog("Max", 5):

  • self becomes max
  • self.name = name means max.name = "Max"

self is like saying “me” or “I”:

Imagine two dogs talking:

  • Buddy says: “MY name is Buddy” (self.name for buddy)
  • Max says: “MY name is Max” (self.name for max)

Same word “my” but refers to whoever is speaking!

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says WOOF!")

buddy = Dog("Buddy")
max = Dog("Max")

buddy.bark()  # Buddy says WOOF!
max.bark()    # Max says WOOF!

Each dog knows its own name because self points to that specific dog!


🎯 Putting It All Together

Let’s build something real—a Student class:

class Student:
    # Class attribute - same for all
    school = "Python Academy"

    # __init__ - automatic setup
    def __init__(self, name, grade):
        # Instance attributes - unique to each
        self.name = name
        self.grade = grade

    # Method using self
    def introduce(self):
        print(f"Hi! I'm {self.name}.")
        print(f"I'm in grade {self.grade}.")
        print(f"I study at {self.school}.")

# Create students (instantiation)
alice = Student("Alice", 5)
bob = Student("Bob", 6)

# Each student introduces themselves
alice.introduce()
# Hi! I'm Alice.
# I'm in grade 5.
# I study at Python Academy.

bob.introduce()
# Hi! I'm Bob.
# I'm in grade 6.
# I study at Python Academy.
graph LR A["Class: Student"] --> B["school = Python Academy"] A --> C["__init__#40;self, name, grade#41;"] A --> D["alice object"] A --> E["bob object"] D --> F["name = Alice"] D --> G["grade = 5"] E --> H["name = Bob"] E --> I["grade = 6"]

🌟 Quick Summary

Concept What It Is Example
Class Blueprint/plan class Dog:
Object Real thing from blueprint buddy = Dog()
Instance Attribute Unique to each object self.name = "Buddy"
Class Attribute Shared by all objects species = "Canine"
__init__ Auto-setup at creation def __init__(self):
self “This object” self.name

🚀 You Did It!

You now understand the building blocks of Object-Oriented Programming in Python:

  1. Class = Your blueprint
  2. Object = What you build from it
  3. Instance attributes = What makes each one unique
  4. Class attributes = What everyone shares
  5. __init__ = Automatic setup at birth
  6. self = “I’m talking about myself”

You’re ready to build anything! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.