📚 Object-Oriented Programming in Python – Core Concepts | 面向对象编程核心概念
Object-Oriented Programming (OOP) is a programming paradigm that organises code around objects rather than functions and logic. In A-Level Computer Science, particularly for Edexcel, you need to understand how classes and objects are defined, how they interact, and why OOP is so powerful for building large, maintainable systems. This article explores every core OOP concept you are expected to master, using Python as the implementation language and linking theory directly to examination requirements.
面向对象编程(OOP)是一种以对象而非函数和逻辑来组织代码的编程范式。在 A-Level 计算机科学,尤其是爱德思考试中,你需要理解如何定义类和对象、它们如何交互,以及为什么 OOP 在构建大型可维护系统时如此强大。本文以 Python 为实现语言,深入探讨你必须掌握的每一个核心 OOP 概念,并将理论与考试要求直接挂钩。
1. Classes and Objects: The Foundation | 类与对象:基础
A class is a blueprint or template that defines the attributes and behaviours an object created from it will possess. An object is a concrete instance of a class, occupying memory and holding actual data. In Python, you use the class keyword to define a class, and call it like a function to create an instance.
类是定义由其创建的对象所拥有的属性和行为的蓝图或模板。对象是类的具体实例,占用内存并持有实际数据。在 Python 中,使用 class 关键字定义类,并像调用函数一样调用它以创建实例。
- Class definition: class Car:
- Class definition (Chinese): class Car: 定义汽车类
- Instantiation: my_car = Car()
- Instantiation (Chinese): my_car = Car() 创建对象
Each object possesses its own copy of instance variables, which means changing one object’s state does not affect another’s. Understanding the distinction between the class itself and its instances is the first step toward writing modular and reusable code.
每个对象都拥有实例变量的独立副本,这意味着改变一个对象的状态不会影响另一个对象。理解类与其本身实例之间的区别,是编写模块化、可重用代码的第一步。
2. Attributes and Methods: State and Behaviour | 属性与方法:状态与行为
Attributes are variables that belong to an object (or class). Instance attributes represent the current state of an object, while methods are functions defined inside a class that describe the object’s behaviours. In Python, the first parameter of an instance method is always self, which refers to the current object.
属性是属于对象(或类)的变量。实例属性表示对象的当前状态,而方法是在类内部定义的、描述对象行为的函数。在 Python 中,实例方法的第一个参数始终是 self,它指向当前对象。
Example: class BankAccount with attribute balance and method deposit(amount).
示例:类 BankAccount 包含属性 balance 和方法 deposit(amount)。
| Concept | Description |
|---|---|
| Instance attribute | Defined within methods using self, e.g. self.balance = 0 |
| Instance method | Defines behaviour; receives self as first argument |
Encapsulating data and the operations that manipulate that data together is the essence of OOP. Edexcel exam questions often ask you to define a class with appropriate attributes and methods, so practising this structure is essential.
将数据与操作数据的方法封装在一起,正是 OOP 的精髓。爱德思考题经常要求你定义一个包含适当属性和方法的类,因此练习这种结构至关重要。
3. Constructors and the __init__ Method | 构造方法与 __init__ 方法
A constructor is a special method automatically called when an object is created. In Python, the constructor is __init__. It allows you to set up initial values for the object’s attributes, ensuring that an object starts its life in a valid state. Any arguments passed during object creation are forwarded to __init__.
构造方法是在创建对象时自动调用的特殊方法。在 Python 中,构造方法是 __init__。它允许你为对象属性设置初始值,确保对象从有效状态开始其生命周期。创建对象时传递的任何参数都会转发给 __init__。
Example: def __init__(self, name, age): sets self.name = name and self.age = age.
示例:def __init__(self, name, age): 设置 self.name = name 和 self.age = age。
The constructor does not return any value (except None implicitly). If you do not define an __init__ method, Python provides a default constructor that does nothing. However, for useful classes, you almost always need to write your own initialiser.
构造方法不返回任何值(隐式地返回 None)。如果不定义 __init__ 方法,Python 会提供一个不做任何事的默认构造方法。然而,对于有用的类,你几乎总是需要编写自己的初始化方法。
4. Encapsulation and Data Hiding | 封装与数据隐藏
Encapsulation means bundling data and methods within a single unit (the class) and restricting direct access to some of the object’s components. This protects the internal state from unintended interference. In Python, encapsulation is implemented by naming conventions: a single underscore prefix (_) indicates a protected attribute, and a double underscore (__) triggers name mangling to make an attribute harder to access from outside the class.
封装意味着将数据和方法捆绑在单个单元(类)中,并限制对对象某些组件的直接访问。这保护了内部状态免受意外干扰。在 Python 中,封装通过命名约定实现:单下划线前缀(_)表示受保护的属性,双下划线(__)触发名称修饰,使属性更难从类外部访问。
- Public: self.balance – accessible from anywhere
- Protected: self._pin – indicates internal use; still accessible but by convention should not be modified directly
- Private: self.__password – Python renames it to _ClassName__password, deterring accidental access
Using getter and setter methods (or the @property decorator) provides controlled access to internal data. For Edexcel, you should be able to explain why encapsulation improves code maintainability and security.
使用获取方法和设置方法(或 @property 装饰器)可以提供对内部数据的受控访问。对于爱德思考试,你应该能够解释封装为何能提高代码的可维护性和安全性。
5. Inheritance: Creating Class Hierarchies | 继承:创建类层次结构
Inheritance allows a new class (child or subclass) to take on the attributes and methods of an existing class (parent or superclass). The child class can then extend or override the parent’s functionality. In Python, inheritance is specified by passing the parent class as an argument: class Child(Parent):.
继承允许新类(子类或派生类)获取现有类(父类或超类)的属性和方法。子类随后可以扩展或重写父类的功能。在 Python 中,通过在类定义中传入父类作为参数来指定继承:class Child(Parent):。
This promotes code reuse and a logical “is-a” relationship. For example, a SavingsAccount is a BankAccount, so it inherits from BankAccount but may add an interest rate attribute. Python supports multiple inheritance, but this can lead to complexity and is introduced carefully.
这促进了代码重用和逻辑上的“是一种”关系。例如,SavingsAccount 是一种 BankAccount,因此它继承自 BankAccount,但可能增加一个利率属性。Python 支持多重继承,但这可能导致复杂性,需要谨慎引入。
| Term | Meaning |
|---|---|
| Superclass | The parent class being inherited from |
| Subclass | The child class that inherits |
| super() | Function used to call a method from the parent class |
In Edexcel exams, you might be presented with a class diagram and asked to implement the hierarchy in code, or to identify superclass and subclass relationships.
在爱德思考试中,你可能会看到一个类图,并被要求用代码实现该层次结构,或者识别父类和子类关系。
6. Polymorphism: Many Forms, One Interface | 多态:多种形态,同一接口
Polymorphism comes from Greek words meaning “many shapes.” In OOP, it refers to the ability of objects of different classes to respond to the same method call in their own way. This is typically achieved through method overriding, where a subclass provides a specific implementation of a method already defined in its superclass.
多态一词源自希腊语,意为“多种形态”。在面向对象编程中,它指的是不同类的对象能够以自己的方式响应相同的方法调用。这通常通过方法重写实现,即子类为其父类中已定义的方法提供特定实现。
Consider a base class Shape with a method draw(). Subclasses Circle and Rectangle each implement draw() differently. A loop processing a list of Shape objects can call draw() on each without knowing the exact type, and the appropriate version runs. This is dynamic polymorphism, made possible by late binding.
考虑一个基类 Shape,它有一个方法 draw()。子类 Circle 和 Rectangle 分别以不同方式实现 draw()。一个处理 Shape 对象列表的循环可以对每个对象调用 draw(),而无需知道确切类型,正确的版本就会运行。这是动态多态,通过后期绑定实现。
Polymorphism is a fundamental concept tested in Edexcel; you must be able to trace code that uses polymorphic method calls and explain the output.
多态是爱德思考试的基础概念;你必须能够追踪使用多态方法调用的代码并解释输出。
7. Method Overriding and Overloading | 方法重写与重载
Method overriding occurs when a subclass provides a new implementation for a method inherited from its superclass, with the same name and signature. This is the primary tool for achieving polymorphism. To call the overridden method from within the new one, use super().method_name().
方法重写发生在子类为从父类继承的方法提供一个新实现时,该方法具有相同的名称和签名。这是实现多态的主要工具。要在新方法内部调用被重写的方法,应使用 super().method_name()。
Method overloading, on the other hand, refers to having multiple methods with the same name but different parameter lists. Python does not support traditional overloading directly; you can achieve a similar effect using default arguments or *args. Edexcel syllabus mentions overloading as a concept, but illustrates it using pseudocode.
另一方面,方法重载是指拥有多个同名但参数列表不同的方法。Python 不直接支持传统的重载;你可以使用默认参数或 *args 实现类似效果。爱德思大纲将重载作为一个概念提及,但使用伪代码进行说明。
- Overriding: Redefining a parent’s method in a child class – same signature, different behaviour.
- Overloading: Multiple methods with the same name but different parameters – requires adaptation in Python.
Knowing the difference is vital; exam questions frequently ask you to distinguish between the two with clear examples.
了解区别至关重要;考题经常要求你通过清晰的示例区分两者。
8. Abstract Classes and Interfaces | 抽象类与接口
An abstract class is a class that cannot be instantiated and is designed to serve as a base for other classes. It may contain abstract methods (methods without a body) that must be implemented by concrete subclasses. In Python, the abc module with the @abstractmethod decorator is used to define abstract classes.
抽象类是无法实例化、设计用作其他类基类的类。它可能包含抽象方法(没有方法体的方法),这些方法必须由具体子类实现。在 Python 中,使用带有 @abstractmethod 装饰器的 abc 模块来定义抽象类。
An interface is a collection of abstract methods that a class promises to implement. Python does not have a formal interface keyword, but abstract classes with only abstract methods serve as interfaces. This enforces consistent behaviour across diverse classes, which is a key principle of OOP design.
接口是一组抽象方法的集合,某个类承诺实现这些方法。Python 没有正式的接口关键字,但仅包含抽象方法的抽象类可作为接口。这强制要求不同类之间行为一致,是 OOP 设计的关键原则。
Example from Edexcel pseudocode: ABSTRACT CLASS Vehicle with ABSTRACT METHOD move().
爱德思伪代码示例:ABSTRACT CLASS Vehicle 包含 ABSTRACT METHOD move()。
9. Relationships Between Classes: Association, Aggregation, Composition | 类之间的关系:关联、聚合、组合
Classes do not exist in isolation; they form relationships. Association is a general “uses-a” relationship where objects of one class interact with objects of another. Aggregation is a “has-a” relationship where the part can exist independently of the whole (e.g., a Department has Employees, but an Employee can exist without a specific Department). Composition is a stronger “has-a” relationship where the part cannot exist without the whole (e.g., a House has Rooms; if the House is destroyed, the Rooms cease to exist).
类并非孤立存在;它们形成关系。关联是一种广义的“使用”关系,一个类的对象与另一个类的对象交互。聚合是一种“含有”关系,其中部分可以独立于整体存在(例如,部门拥有员工,但员工可以在没有特定部门的情况下存在)。组合是一种更强的“含有”关系,其中部分不能脱离整体存在(例如,房子有房间;如果房子被毁,房间也就不复存在了)。
| Relationship | Symbol (UML) | Lifetime dependency |
|---|---|---|
| Association | Simple line | None |
| Aggregation | Empty diamond at whole end | Part can outlive whole |
| Composition | Filled diamond at whole end | Part is destroyed with whole |
Edexcel expects you to identify these relationships from class diagrams and explanation snippets, and to choose the appropriate type when designing systems.
爱德思期望你从类图和解释片段中识别这些关系,并在设计系统时选择适当的类型。
10. Static Methods and Class Methods | 静态方法与类方法
Instance methods operate on a specific object and receive self. However, there are methods that belong to the class itself rather than to any instance. A static method, decorated with @staticmethod, does not receive any implicit first argument and behaves like a regular function defined inside a class namespace. A class method, decorated with @classmethod, receives the class itself as the first argument (conventionally cls).
实例方法操作特定对象并接收 self。然而,有些方法属于类本身而非任何实例。静态方法使用 @staticmethod 装饰,不接收任何隐式的第一个参数,其行为类似于在类命名空间内定义的常规函数。类方法使用 @classmethod 装饰,接收类自身作为第一个参数(按惯例称为 cls)。
- staticmethod: Used when no access to instance or class data is needed, e.g., a utility conversion function.
- classmethod: Commonly used as alternative constructors that can create instances from different data formats.
Static and class methods show an understanding that not all behaviour depends on instance state. They appear in Edexcel algorithms often when describing factory methods or helper routines.
静态方法和类方法表明你理解并非所有行为都依赖于实例状态。它们在描述工厂方法或辅助程序时经常出现在爱德思算法中。
11. Advantages of Object-Oriented Programming | 面向对象编程的优势
OOP offers concrete benefits that make it the dominant paradigm for modern software development. Reusability is achieved through inheritance and composition. Modularity is enhanced because each class forms a self-contained unit. Encapsulation increases security and reduces side effects. Polymorphism enables flexibility and easier maintenance.
面向对象编程提供了切实的优势,使其成为现代软件开发的主导范式。通过继承和组合实现重用性。由于每个类构成一个自包含单元,模块化得到增强。封装提高了安全性并减少副作用。多态实现了灵活性和更轻松的维护。
- Code reusability: Inherit and extend existing code.
- Real-world modelling: Objects mirror real entities, aiding design.
- Improved maintainability: Changes in one class have limited impact.
- Scalability: Large systems can be split into manageable objects.
In Edexcel exams, you may be asked to evaluate why OOP was chosen for a particular scenario, comparing it to procedural or functional approaches.
在爱德思考试中,你可能会被要求评估为何在特定情境中选择 OOP,并将其与过程式或函数式方法进行比较。
12. Common Pitfalls and Exam Tips | 常见陷阱与应试技巧
When implementing OOP in Python, beginners often forget to include self as the first parameter of instance methods, leading to mysterious TypeError messages. Another common mistake is accidentally sharing mutable default arguments across instances, such as a list default parameter. Additionally, confusing the class definition with object instantiation can cause logical errors.
在 Python 中实现 OOP 时,初学者经常忘记在实例方法中包含 self 作为第一个参数,从而导致令人困惑的 TypeError 消息。另一个常见错误是在实例之间意外共享了可变默认参数,例如列表默认参数。此外,混淆类定义与对象实例化可能导致逻辑错误。
For Edexcel written exams, practise reading and interpreting class diagrams; be prepared to translate between pseudocode and Python where required. Understand that abstract, static, and overridden methods must be clearly annotated. When explaining concepts, always support your answer with a short, concrete example.
对于爱德思笔试,请练习阅读和解释类图;准备好按要求在伪代码和 Python 之间进行转换。理解抽象方法、静态方法和重写方法必须明确标注。在解释概念时,始终用一个简短具体的例子来支撑你的答案。
Time management is crucial: questions often ask you to write class definitions within a limited answer space, so practise writing complete but concise code under timed conditions.
时间管理至关重要:题目经常要求你在有限的答题空间内编写类定义,因此请练习在限时条件下写出完整而简洁的代码。
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课程辅导,国外大学本科硕士研究生博士课程论文辅导