📚 Object-Oriented Programming: Classes, Inheritance and Polymorphism | 面向对象编程:类、继承与多态
Object-oriented programming (OOP) is a central part of Edexcel A-Level Computer Science Topic 6: Problem solving with programming. This article explains OOP concepts in a practical way, using Python-style examples to help you answer exam questions on classes, inheritance, polymorphism and encapsulation.
面向对象编程(OOP)是 Edexcel A-Level 计算机科学主题 6“用编程解决问题”的核心内容。本文以实用方式讲解 OOP 概念,并借助 Python 风格示例,帮助你解答关于类、继承、多态和封装的考试题目。
1. Why Programming Paradigms Matter | 为什么编程范式重要
A programming paradigm is a style or way of thinking about how to structure code. Edexcel expects you to compare paradigms, especially procedural and object-oriented. Procedural programming organises code as a sequence of instructions, functions and data passed between them. OOP organises code around objects that combine data and behaviour. Understanding the difference helps you choose suitable designs and justify choices in exam answers.
编程范式是一种组织代码结构的思维方式。Edexcel 要求你比较不同范式,尤其是面向过程与面向对象。面向过程编程将代码组织为一系列指令、函数以及它们之间传递的数据。OOP 则围绕对象来组织代码,对象将数据和行为结合在一起。理解两者的区别有助于在考试中做出合理设计并论证选择。
- Procedural = step-by-step instructions + separate data | 面向过程 = 逐步指令 + 分离的数据
- Object-oriented = objects with attributes and methods | 面向对象 = 具有属性和方法的对象
2. Procedural vs Object-Oriented Thinking | 面向过程与面向对象的思维对比
In procedural programming, a banking system might have functions like deposit(account, amount) and withdraw(account, amount), with account stored as a dictionary and passed each time. In OOP, account is an object with attributes (balance, owner) and methods (deposit, withdraw) already attached. This makes OOP more modular for large systems, because related data and functions stay in one place.
在面向过程编程中,银行系统可能编写 deposit(account, amount) 和 withdraw(account, amount) 这样的函数,账户以字典形式存储并每次传递。而在 OOP 中,账户是一个对象,自带属性(余额、所有者)和方法(存款、取款)。这使得 OOP 对大型系统更模块化,因为相关数据和函数保存在同一个位置。
| Procedural | Object-oriented |
|---|---|
| Data and functions separate | Data and methods bundled in objects |
| Focus on steps and procedures | Focus on entities and their interactions |
| Code reuse via functions | Code reuse via inheritance and composition |
3. Classes and Objects: The Blueprint Analogy | 类与对象:蓝图类比
A class is a blueprint or template; an object is a concrete instance created from that class. For example, Dog is a class, while my_dog = Dog(“Rex”) creates one Dog object. Edexcel questions often ask you to identify the class and the object in a scenario. Use the analogy of a cookie cutter (class) and cookies (objects): the cutter defines shape, but each cookie can have different icing or size.
类是一个蓝图或模板;对象是根据该类创建的具体实例。例如,Dog 是一个类,而 my_dog = Dog(“Rex”) 创建了一个 Dog 对象。Edexcel 题目经常要求识别场景中的类和对象。可以用模具(类)和饼干(对象)类比:模具决定形状,但每块饼干可以有不同的糖霜或大小。
class Dog:
def __init__(self, name):
self.name = name
my_dog = Dog("Rex")
Here, Dog is the class and my_dog is one instance of that class. | 这里,Dog 是类,my_dog 是该类的一个实例。
4. Attributes and Methods: Data + Behaviour | 属性和方法:数据 + 行为
Attributes are variables that belong to an object; they store its state. Methods are functions that belong to a class; they define behaviour. In a Car class, attributes include speed, fuel, colour; methods include accelerate(), brake(), refuel(). The constructor (in Python, __init__) sets initial attribute values. Exam answers should use accurate terms: attribute, method, constructor, not just “variable” and “function” when talking about OOP.
属性是属于对象的变量,用于存储状态。方法是属于类的函数,用于定义行为。在 Car 类中,属性包括速度、油量、颜色;方法包括加速、刹车、加油。构造函数(Python 中为 __init__)用于设置属性的初始值。考试答案应使用准确术语:属性、方法、构造函数,而不是在讨论 OOP 时仅仅说“变量”和“函数”。
- Attribute: stores state, e.g. self.speed = 0 | 属性:存储状态,如 self.speed = 0
- Method: defines behaviour, e.g. def accelerate(self, amount) | 方法:定义行为,如 def accelerate(self, amount)
- Constructor: initialises attributes when object is created | 构造函数:创建对象时初始化属性
5. Encapsulation: Protecting Internal State | 封装:保护内部状态
Encapsulation means hiding the internal details of an object and exposing only what is necessary through methods. This prevents invalid changes, such as setting a bank balance to a negative value directly. In Python, a common convention is to prefix an attribute with an underscore (e.g., _balance) and provide getter/setter methods. Edexcel may ask why encapsulation is important: it improves maintainability, security and reduces unintended interference between components.
封装意味着隐藏对象的内部细节,只通过方法暴露必要内容。这可以防止无效修改,例如直接将银行余额设为负数。在 Python 中,常见约定是给属性加下划线前缀(如 _balance),并提供 getter/setter 方法。Edexcel 可能考查封装为什么重要:它提高了可维护性和安全性,减少了组件之间的意外干扰。
- Data integrity: attributes can be validated before changing | 数据完整性:属性在修改前可进行验证
- Loose coupling: objects interact through well-defined methods | 松散耦合:对象通过定义良好的方法进行交互
- Easier maintenance: internal representation can change without breaking outside code | 易于维护:内部表示改变不会破坏外部代码
6. Inheritance: Reusing and Extending Classes | 继承:复用与扩展类
Inheritance allows a new class (subclass/derived class) to inherit attributes and methods from an existing class (superclass/base class). For example, Animal is a superclass; Dog and Cat are subclasses that inherit eat() and sleep() but define their own speak(). This avoids code duplication and models “is-a” relationships. In exams, you may be asked to draw a class diagram or identify superclass/subclass from a description.
继承允许新类(子类/派生类)从已有类(父类/基类)继承属性和方法。例如,Animal 是父类;Dog 和 Cat 是子类,它们继承 eat() 和 sleep(),但定义各自的 speak()。这避免了代码重复,并建模“是(is-a)”关系。考试中可能要求画类图或根据描述识别父类与子类。
| Class | Inherits from | Overrides |
|---|---|---|
| Animal | Object | – |
| Dog | Animal | speak() |
| Cat | Animal | speak() |
7. Polymorphism: One Interface, Many Forms | 多态:一个接口,多种形态
Polymorphism means “many forms”: the same method name can behave differently in different classes. If Dog and Cat both have speak(), code can call animal.speak() without knowing which specific type animal is. This is useful when processing lists of objects. Edexcel often combines polymorphism with inheritance: subclasses override methods to provide their own implementation. A method overriding occurs when a subclass defines a method with the same signature as the superclass.
多态意思是“多种形态”:相同的方法名可以在不同类中表现出不同行为。如果 Dog 和 Cat 都有 speak(),代码可以调用 animal.speak(),而无需知道 animal 具体是哪种类型。这在处理对象列表时非常有用。Edexcel 经常将多态与继承结合考查:子类重写(override)方法以提供自己的实现。当子类定义与父类相同签名的方法时,就发生了方法重写。
Example: | 示例:
for animal in animals:
animal.speak()
The same call speak() produces “Woof” for Dog or “Meow” for Cat. | 同样的调用 speak() 对于 Dog 会产生“Woof”,对于 Cat 会产生“Meow”。
8. Abstract Classes and Interfaces | 抽象类与接口
An abstract class is a class that cannot be instantiated directly; it exists to be inherited. Abstract methods are declared with no implementation, forcing subclasses to provide concrete behaviour. For example, an abstract Shape class has method area(), but cannot create a Shape object; Circle and Square must implement area(). Interfaces are similar, specifying method signatures without any data. Edexcel may ask you to explain the purpose: to define a common contract.
抽象类是不能直接实例化的类,其存在是为了被继承。抽象方法只声明不实现,迫使子类提供具体行为。例如,抽象类 Shape 有 area() 方法,但不能创建 Shape 对象;Circle 和 Square 必须实现 area()。接口与之类似,只规定方法签名而不包含数据。Edexcel 可能要求解释其目的:定义一个通用契约。
- Abstract class: may contain partial implementation, cannot instantiate | 抽象类:可包含部分实现,不能实例化
- Interface: only method signatures, no data or implementation | 接口:只有方法签名,没有数据或实现
- Both enforce a design contract on subclasses | 两者都为子类强制设定设计契约
9. Practical Edexcel Exam-Style Application | Edexcel 考试风格实际应用
Consider a question: “A wildlife simulation needs animals to move, eat and make sound. Design OOP classes.” You would identify a base class Animal with attributes name, energy and methods move(), eat(), make_sound(). Then subclasses Bird, Fish, Mammal override move() and make_sound(). Using polymorphism, the simulation can call move() on every animal in a list without repeated if-statements. Encapsulation ensures energy cannot be set below 0 directly. Inheritance avoids rewriting eat() for each subtype. These are the key marks examiners look for.
考虑一道题:“一个野生动物模拟系统需要动物移动、进食和发声。设计 OOP 类。”你应识别出基类 Animal,属性包括 name、energy,方法包括 move()、eat()、make_sound()。然后子类 Bird、Fish、Mammal 重写 move() 和 make_sound()。利用多态,模拟程序可以对列表中的每个动物调用 move(),而无需重复 if 语句。封装确保能量不能直接设为低于 0。继承避免为每个子类型重写 eat()。这些是阅卷人关注的关键得分点。
| Class | Role | Key OOP feature |
|---|---|---|
| Animal | Base class | Encapsulation, shared methods |
| Bird, Fish, Mammal | Subclasses | Inheritance, method overriding |
| Simulation loop | Uses list of Animal objects | Polymorphism |
10. Common Pitfalls and Exam Tips | 常见错误与考试技巧
Common mistakes: confusing class with object, forgetting the constructor role, saying “encapsulation is only about security”, using inheritance when composition is better, and failing to mention method overriding in polymorphism questions. Exam tips: define terms precisely, use examples, relate each OOP concept to a benefit (reuse, maintainability, data integrity), and when asked to evaluate paradigms, always compare procedural vs OOP with a scenario. Edexcel mark schemes reward “because” statements, not just definitions.
常见错误:混淆类与对象、忘记构造函数的作用、认为封装仅与安全有关、在组合更合适时错误使用继承、在多态题中未提及方法重写。考试技巧:准确定义术语、使用示例、将每个 OOP 概念与好处联系起来(复用、可维护性、数据完整性),并且在评价范式时,始终结合场景比较面向过程与 OOP。Edexcel 评分方案奖励“因为……”这样的因果陈述,而不仅仅是定义。
- Always write “an object is an instance of a class” | 始终写出“对象是类的实例”
- Use “overriding” when a subclass redefines a method | 当子类重新定义方法时使用“重写”
- Link OOP benefits to specific scenario details | 将 OOP 的好处与具体场景细节联系起来
Published by TutorHao | Programming Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导