class 扩展

🐍 Lesson: Introduction to Python Classes & Objects

Duration: 90 Minutes | Topic: Object-Oriented Programming (OOP)


Part 1: The "Blueprint" Concept (10 mins)

Goal: Understand why we use classes.

Explanation for Student: Imagine you want to build a house. You don't just start building randomly. You need a Blueprint (a plan).

  • The Class: The Blueprint. It defines what a house has (windows, doors, color).
  • The Object: The actual House. You can use one blueprint to build many houses. Each house can have a different color, but they all follow the same plan.

【笔记】 用乐高(LEGO)做比喻:Class 是说明书,Object 是拼出来的成品。强调:一个 Class 可以创建无数个 Object。


Part 2: Syntax - Our First Class (20 mins)

Goal: Learn class, __init__, and self.

Code Example:

python 复制代码
class Dog:
    # The "Constructor" - This runs when we create a new dog
    def __init__(self, name, breed, age):
        self.name = name    # Attribute
        self.breed = breed  # Attribute
        self.age = age      # Attribute

    # A Method (What the dog can DO)
    def bark(self):
        print(f"{self.name} says: Woof! Woof!")

# --- Creating 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!

Key Concepts for Student:

  1. __init__: The "Starting Point." It sets up the object's information.
  2. self : Refers to "this specific object." When Buddy barks, self.name is Buddy. When Lucy barks, self.name is Lucy.
  3. Attributes: Variables that belong to the object (name, age).
  4. Methods: Functions that belong to the object (bark, run).

【教师笔记】

  • 重点强调 __init__ 是左右各两个下划线。
  • 让学生试着修改 my_dog.age = 4 然后打印输出,展示属性是可以改变的。

Part 3: Interactive Challenge - "Design a Hero" (20 mins)

Goal: Practice creating attributes and basic methods.

Task: Create a class called Hero for an RPG game.

  1. Attributes: name, health (default 100), power.
  2. Method: rest() -> Increases health by 10.
  3. Method: stats() -> Prints the hero's current status.

Solution Template (Don't show the student yet!):

python 复制代码
class Hero:
    def __init__(self, name, power):
        self.name = name
        self.power = power
        self.health = 100

    def rest(self):
        self.health += 10
        print(f"✨ {self.name} is resting. Health is now {self.health}")

    def stats(self):
        print(f"📊 Hero: {self.name} | HP: {self.health} | Power: {self.power}")

# Student should test it:
p1 = Hero("Zelda", 25)
p1.stats()
p1.rest()

【教师笔记】 观察学生是否记得在方法(rest, stats)的括号里写 self。这是新手最容易忘掉的地方。


Part 4: Object Interaction - "The Battle" (20 mins)

Goal: Learn how two objects interact with each other.

Explanation for Student: Objects aren't just isolated. They can interact! We can pass one object into the method of another object.

Code Extension:

python 复制代码
class Hero:
    def __init__(self, name, health, power):
        self.name = name
        self.health = health
        self.power = power

    def attack(self, enemy):
        print(f"⚔️ {self.name} attacks {enemy.name}!")
        enemy.health -= self.power
        print(f"💥 {enemy.name} now has {enemy.health} HP left.")

# Creating two heroes
hero = Hero("Link", 100, 20)
monster = Hero("Ganon", 200, 10)

# Let the interaction happen
hero.attack(monster) 

【笔记】 这是进阶内容。解释 enemy 在这里代表另一个 Hero 对象。这能极大增加课程的趣味性,学生通常很喜欢这种类似游戏的逻辑。


Part 5: Final Boss Task - "The Bank Account" (20 mins)

Goal: Independent coding to consolidate everything.

Instructions for Student: Create a class BankAccount.

  • Attributes: owner (string), balance (number).
  • Method deposit(amount): Adds money to balance.
  • Method withdraw(amount) :
    • If balance is enough: Subtract money.
    • If not enough: Print "Insufficient funds!"
  • Task: Create an account for yourself with 100.Deposit100. Deposit 100.Deposit50. Try to withdraw $200.

【笔记】 如果学生提前完成,可以增加额外挑战:

  1. 增加一个 transfer(self, other_account, amount) 方法,把钱从一个账号转到另一个账号。
  2. 增加一个 is_bankrupt 属性。

Student Cheat Sheet (Print or share this)

Concept Python Syntax Meaning
Create a Class class Name: Define the blueprint
Initialize def __init__(self, ...): Set the starting stats
Identity self Referring to "this specific" object
Action def method_name(self): What the object can do
Instance obj = Name() Making a real thing from the blueprint

Troubleshooting / FAQ

  • Error: TypeError: __init__() takes 3 positional arguments but 4 were given
    • Cause: The student forgot self in the __init__ definition.
  • Error: NameError: name 'health' is not defined
    • Cause: Inside a method, they wrote health instead of self.health.
  • Conceptual Confusion: "Why do we need classes?"
    • Answer: "If we have 100 dogs, without classes, we need 300 variables. With classes, we just need 100 objects."
相关推荐
VidDown5 小时前
24fps 转 25fps 不只是改个数字:帧率转换、PAL/NTSC 与音频补偿
python·网络协议·音视频·视频编解码·视频
死磕音视频7 小时前
让小模型做选择题:限定候选项并读取 logits 概率的入门实践(附 Python 代码)
开发语言·python·大模型·文本分类·transformers
凤山老林8 小时前
Spring Boot 接入国密 SM2/SM3/SM4 的一些实践记录
spring boot·后端·python
pride.li9 小时前
第03章 Python 教程-基础语法:注释与变量
服务器·前端·后端·python·算法·计算机视觉
databook9 小时前
用 Pydantic AI 从零搭建一个能干活的 AI Agent
人工智能·python
康小旺10 小时前
把 markitdown 做成 Windows 桌面版:拖进文档就出 Markdown,附 233MB→64MB 打包裁剪全过程
python
启观川10 小时前
数据结构与算法-第 3 章 常用算法-贪心算法
数据结构·笔记·python·算法·贪心算法
南笙北梦11 小时前
本地开源大模型多轮对话显存泄漏排查与修复实录
python
小羊没烦恼!11 小时前
如何在IIS6,7中部署ASP.NET网站?
数据库·后端·python·web安全·asp.net
钱栈up11 小时前
扫完 3.5 万文件后,我发现了 521 组散落的同名文件
爬虫·python·数据分析