Classes(类)学习笔记总结

AI1个月前发布 beixibaobao
19 0 0

1️⃣ 为什么要学 Class?

一句话动机

Class 是用来“描述一类东西”的,把数据 + 行为绑在一起

不用 class:

x = 3 y = 4 vx = 1 vy = 2

用了 class:

particle.position particle.velocity particle.move()

👉 逻辑更清楚,也更像真实世界


2️⃣ 什么是 Class / Object(先搞清概念)

名字 含义
class 模板 / 蓝图
object (instance) 用模板造出来的具体东西

类比:

  • class Car → 汽车设计图

  • my_car = Car() → 你的一辆车


3️⃣ 定义一个最基本的 Class

class Dog: def bark(self): print("woof")

使用:

d = Dog() d.bark()

👉 这里:

  • Dog 是类

  • d 是对象

  • bark 是方法(method)


4️⃣ __init__:构造函数(非常重要)

作用

在“造对象”的那一刻初始化数据

class Dog: def __init__(self, name): self.name = name def bark(self): print(self.name, "says woof")

使用:

d = Dog("Lucky") d.bark()


关键点(必背)

  • __init__ 不是创建对象

  • 是对象创建后 自动执行

  • self 指当前这个对象


5️⃣ self 到底是啥?(重点中的重点)

一句话解释

self 就是“这个对象自己”

d1 = Dog("A") d2 = Dog("B")

  • d1.named2.name

  • self.name = 当前对象的 name

⚠️ self 不是关键字,只是约定俗成的名字


6️⃣ Attribute(属性) vs Method(方法)

class Circle: def __init__(self, r): self.radius = r # attribute def area(self): # method return 3.14 * self.radius**2

使用:

c = Circle(2) c.radius c.area()


7️⃣ Inheritance(继承)

核心思想

子类“继承”父类的属性和方法

class Animal: def speak(self): print("I make a sound") class Dog(Animal): def speak(self): print("woof")

使用:

d = Dog() d.speak()


你之前问的那个问题答案在这👇

👉 子类定义了同名方法,会覆盖父类方法

这叫:

method overriding(方法重写)


8️⃣ Polymorphism(多态)

一句话版本

同一个方法名,不同对象,行为不同

animals = [Dog(), Animal()] for a in animals: a.speak()

输出:

woof I make a sound

👉 Python 看的是:

  • 对象“是什么”

  • 而不是变量名字


9️⃣ Class 里常见的“魔法方法”(你 note 里可能有)

方法 作用
__init__ 初始化
__str__ print(obj) 时显示
__len__ len(obj)
__repr__ 调试显示

示例:

def __str__(self): return f"Circle with r={self.radius}"


🔟 Class vs Function(很多人混)

对比 function class
状态 ❌ 没有 ✅ 有
复杂系统
面向对象

👉 函数是“做一件事”
👉 类是“描述一个东西”


1️⃣1️⃣ Class + Module(和 Notebook 7 连起来)

现实写法:

geometry.py

class Circle: ... class Rectangle: ...

使用:

from geometry import Circle c = Circle(2)

👉 类通常放在 module 里


1️⃣2️⃣ 常见错误(考试 & 作业雷区)

❌ 忘写 self
❌ 用 Class.method() 调实例方法
❌ 以为 __init__ 创建对象
❌ 不理解覆盖(override)

© 版权声明

相关文章