Skip to content

类

一句话解释

类 是 blueprint for 创建 对象, 定义 使用 类 keyword, 那个 bundles 数据 (attributes) and behavior (方法).

用大白话说

类是 template or blueprint for 创建对象. 它定义什么 attributes (数据) and 方法 (behavior) 对象的 那个类型将 有. 你定义类 使用 class keyword.

The __init__ method is the constructor — it runs when you create a new instance and initializes its attributes. Methods are functions defined inside the class; they take self as the first parameter to access the instance.

Classes support inheritance (a class can extend another), encapsulation (hiding internal state), and polymorphism (different classes can have methods with the same name). Classes are the foundation of object-oriented programming in Python.

示例

python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says Woof!"

rex = Dog("Rex", 3)
print(rex.name)    # Rex
print(rex.bark())  # Rex says Woof!

类 是 定义 使用 类, initialized 使用 __init__, and 方法 use self 到 access 实例 数据.

常见混淆

  • 容易混淆的对象: 对象

    关键区别: 类 是 blueprint/template. 对象 (实例) 是 特定 thing 创建 从 那个 类. 类 定义 结构; 对象 是 具体 realization 使用 它的 own 数据.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表