python - class 入门

🐍 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 :

  1. Missing comma in init

  2. Missing self.name

  3. 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.

  1. Attributes: name, type (e.g., Fire), and level (start at level 1).
  2. Method say_hello(): Print "Pika Pika! I am [name]".
  3. Method level_up(): Increase the level by 1.
  4. 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 owner and balance.
  • 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 的"顿悟时刻"。

相关推荐
PAK向日葵2 小时前
我用 C++ 写了一个轻量级 Python 虚拟机,刚刚开源
c++·python·开源
财经资讯数据_灵砚智能4 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年5月26日
大数据·人工智能·python·信息可视化·自然语言处理·ai编程·灵砚智能
我材不敲代码4 小时前
Python基础:列表详解、增删改查及常用高阶操作
开发语言·windows·python
AI玫瑰助手4 小时前
Python运算符:成员运算符(in/not in)的使用场景
开发语言·python·信息可视化
水木流年追梦5 小时前
大模型入门-大模型分布式训练2
开发语言·分布式·python·算法·正则表达式·prompt
ZHANG8023ZHEN5 小时前
Diffusion 数学推理
人工智能·python·机器学习
海天一色y5 小时前
SGLang 本地部署 Qwen3-8B 大模型实战指南
python·sglang
代码帮6 小时前
面试题 - GIL全局解释器锁 :为什么Python多线程不能利用多核?GIL对I/O密集和CPU密集任务的影响?如何绕过GIL(多进程、C扩展)
python·面试
徐安安ye6 小时前
FlashAttention流式输出:Streaming Chunked Attention与增量解码
人工智能·pytorch·python