🐍 Lesson: Python Classes & Objects
The Ultimate Blueprint for Everything!
1. The Concept: Blueprints vs. Objects
Imagine you want to build a house. You don't just start stacking bricks randomly. You need a Blueprint first.
- The Class (The Blueprint): A plan that says what a house should have (windows, doors, color).
- The Object (The Real House): The actual house built from the blueprint. You can use the same blueprint to build 100 different houses with different colors!
【备注】 这里可以用乐高做比喻。Class 是乐高的说明书,Object 是拼出来的成品。一个说明书可以拼出无数个一模一样的成品。
2. Our First Class: Creating a Pet 🐶
In Python, we use the keyword class to create a blueprint.
python
class Dog:
# 1. The Constructor: How to "birth" a dog
def __init__(self, name, breed, age):
self.name = name # Setting the name tag
self.breed = breed # Setting the breed tag
self.age = age # Setting the age tag
# 2. A Method: Something the dog can DO
def bark(self):
print(f"{self.name} says: Woof! Woof!")
def celebrate_birthday(self):
self.age += 1
print(f"Happy Birthday {self.name}! You are now {self.age} years old.")
# --- Creating real objects ---
my_dog = Dog("Buddy", "Golden Retriever", 3)
your_dog = Dog("Lucy", "Poodle", 5)
print(my_dog.name) # Output: Buddy
my_dog.bark() # Output: Buddy says: Woof! Woof!
your_dog.celebrate_birthday() # Output: Lucy is now 6!
【备注】
- 强调
__init__前后有两个下划线。- 解释
self:它是"自己"的意思。告诉小孩:当 Buddy 说话时,self.name就是 Buddy;当 Lucy 说话时,self.name就是 Lucy。
3. Game Time: Creating a Hero ⚔️
Classes are perfect for video games. Let's make a Hero for an RPG!
python
class Hero:
def __init__(self, name, power):
self.name = name
self.power = power
self.health = 100
self.inventory = []
def stats(self):
print(f"Hero: {self.name} | Power: {self.power} | HP: {self.health}")
def take_damage(self, amount):
self.health -= amount
print(f"Ouch! {self.name} lost {amount} HP!")
if self.health <= 0:
print(f"Game Over! {self.name} has fainted.")
def find_item(self, item):
self.inventory.append(item)
print(f"{self.name} found a {item}!")
# Let's play!
player = Hero("SuperZelda", "Lightning Strike")
player.stats()
player.find_item("Golden Sword")
player.take_damage(30)
print(f"Inventory now: {player.inventory}")
【备注】 这个例子展示了 Class 内部可以包含
list(inventory)。可以问她:"如果你想给 Hero 加一个'蓝量 (Mana)',你会怎么改代码?"
4. More Examples: Real World Things 🌎
Example A: The Minecraft Block
python
class Block:
def __init__(self, material, color):
self.material = material
self.color = color
self.durability = 10
def mine(self):
self.durability -= 2
if self.durability > 0:
print(f"Mining {self.material}... {self.durability} left.")
else:
print(f"The {self.material} block broke!")
dirt = Block("Dirt", "Brown")
dirt.mine()
Example B: The Smartphone
python
class Phone:
def __init__(self, brand, model):
self.brand = brand
self.model = model
self.battery = 100
def watch_youtube(self, minutes):
drain = minutes * 1
self.battery -= drain
print(f"Watched YouTube for {minutes} mins. Battery: {self.battery}%")
def charge(self):
self.battery = 100
print("Phone is fully charged!")
my_phone = Phone("Apple", "iPhone 15")
my_phone.watch_youtube(20)
5. Quiz & Practice Section 📝
Task 1: Spot the Bug! 🐛
There are 3 mistakes in the code below. Can you find them?
python
class Cat:
def __init__(self name):
name = name
def meow()
print("Meow!")
my_cat = Cat("Kitty")
my_cat.meow()
Answers :
-
Missing comma in init
-
Missing self.name
-
Missing self in meow method
Task 2: Fill in the Blanks
Complete the code to make the car move!
python
class Car:
def __init__(self, brand, color):
self.brand = ____
self.fuel = 100
def drive(self):
self.fuel -= 10
print(f"The {self.color} {self.brand} is driving! Fuel: {self.fuel}")
my_car = ____("Tesla", "Red")
my_car.____()
Task 3: The "Pokemon" Challenge (Coding Task) 🎮
Goal: Create a Pokemon class.
- Attributes:
name,type(e.g., Fire), andlevel(start at level 1). - Method
say_hello(): Print "Pika Pika! I am [name]". - Method
level_up(): Increase thelevelby 1. - Action: Create a Pokemon named "Pikachu", make it say hello, level it up, and print its new level.
Task 4: The "Logic Master" Challenge 🧠
What will the code print?
python
class Robot:
def __init__(self, name):
self.name = name
r1 = Robot("Robbie")
r2 = Robot("BeepBoop")
r1.name = "Flash"
print(r1.name)
print(r2.name)
Question: Will r2's name change to "Flash" too? Why or why not?
Task 5: The "Bank Account" (Final Boss Task) 💰
Write a class called BankAccount.
- It should have
ownerandbalance. - A method
deposit(amount)that adds money. - A method
withdraw(amount)that checks:- If you have enough money, subtract it.
- If you DON'T have enough, print "No money left!".
💡 Quick Cheat Sheet for the Student:
class Name:-> Always capitalize the Class name.def __init__(self, ...):-> The "Starting Point" for every object.self.variable-> A variable that belongs to the object.my_object = Name()-> Creating the object.my_object.method()-> Telling the object to do something.
【备注】 可以挑战她:让两个 Object 互动。比如
hero.attack(monster),把一个对象传进另一个对象的方法里。这将是她理解 OOP 的"顿悟时刻"。