🎯 What you will learn
- Define a class with __init__
- Create objects with their own attributes
- Write methods that use self
👋 Let’s get started!
A class is a blueprint 📐; objects are the things built from it. One “Pet” class can create thousands of different pets, each with its own name and mood. This is object-oriented programming (OOP), used in almost every big app.
🪜 Step by step
1. 📐 Blueprint
class defines the blueprint. __init__ runs when an object is created.
class Pet:
def __init__(self, name, species):
self.name = name
self.species = species
2. 🐶 Objects
Call the class like a function to build objects.
rex = Pet("Rex", "dog")
mia = Pet("Mia", "cat")
print(rex.name, mia.species)
3. ⚙️ Methods
Methods are functions inside a class. self means “this object”.
class Pet:
def __init__(self, name):
self.name = name
self.hunger = 5
def feed(self):
self.hunger -= 2
print(f"{self.name} munches. Hunger: {self.hunger}")
🧪 Try it!
Change the code and press ▶ Run to see what happens. You can’t break anything!
Virtual pet
class Pet:
def __init__(self, name):
self.name = name
self.happiness = 5
def play(self):
self.happiness += 2
return f"{self.name} chases the ball! 😄 ({self.happiness})"
def __str__(self):
return f"Pet {self.name} with happiness {self.happiness}"
buddy = Pet("Buddy")
print(buddy.play())
print(buddy.play())
print(buddy)Build a BankAccount class
class BankAccount:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
self.balance += amount📖 Key words
Tap a card to flip it over!
- Class
- A blueprint for objects 📐
- Object
- A thing built from a class 🧱
- Attribute
- Data stored in an object 🏷️
- self
- The current object 🪞
🏆 Challenge
Finish the Rectangle class so area() returns width × height. The program should print 12.
Challenge
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
pass
print(Rectangle(3, 4).area())Knowledge Check Quiz
- What does __init__ do?
- What prints?
- A class is like a…