📚 Object-Oriented Programming: Core Concepts and A-Level Python Applications | 面向对象编程:核心概念与A-Level Python应用实例
Object-oriented programming (OOP) is a design paradigm widely adopted in modern software development and assessed at A-Level. It centres on modelling data and behaviour together inside reusable structures called objects, making complex systems easier to maintain, extend and debug. This article explores core OOP principles and shows practical Python examples aligned with the Edexcel specification.
面向对象编程(OOP)是现代软件开发中广泛采用的设计范式,也是 A-Level 考评的核心内容。它以可复用的结构——对象——为中心,将数据和行为封装在一起,使复杂系统更易于维护、扩展和调试。本文将探讨核心 OOP 原则,并结合 Edexcel 规范展示实用的 Python 示例。
1. What Is Object-Oriented Programming? | 什么是面向对象编程?
OOP is a programming methodology that treats data as self-contained objects. Each object bundles its own attributes (state) and methods (behaviour). Unlike procedural programming, where functions operate on separate data, OOP defines classes as blueprints to create objects. Key concepts like inheritance, polymorphism and encapsulation help reduce redundancy and improve clarity.
OOP 是一种将数据视为自包含对象的编程方法。每个对象都包裹着自己的属性(状态)和方法(行为)。与函数操作分离数据的过程式编程不同,OOP 将类定义为创建对象的蓝图。继承、多态和封装等关键概念有助于减少冗余并提高清晰度。
2. Defining Classes and Creating Objects | 定义类和创建对象
A class is a template for creating instances. In Python, you use the class keyword followed by a name (PascalCase by convention). The __init__ method initialises instance attributes. For example, a Student class might store name and grade:
类是用于创建实例的模板。在 Python 中,使用 class 关键字后跟名称(按惯例使用 PascalCase)。__init__ 方法用于初始化实例属性。例如,Student 类可以存储姓名和成绩:
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
To instantiate an object, call the class as if it were a function: s1 = Student('Alex', 'A'). The variable s1 now references an object with its own name and grade.
要实例化对象,可以像调用函数一样调用类:s1 = Student('Alex', 'A')。变量 s1 现在引用一个包含自身 name 和 grade 的对象。
3. Instance Attributes and Methods | 实例属性与方法
Instance attributes are variables bound to a specific object, typically defined inside __init__ using self.attribute. Methods are functions defined inside the class. The first parameter of a method must be self, which refers to the calling instance. In a BankAccount class, deposit and withdraw methods alter the balance attribute.
实例属性是绑定到特定对象的变量,通常在 __init__ 内部通过 self.attribute 定义。方法是在类内部定义的函数,方法的第一个参数必须是 self,它引用调用该方法的实例。在 BankAccount 类中,deposit 和 withdraw 方法会修改 balance 属性。
This binding ensures each object maintains its own state independently, a founding principle of OOP. You access an attribute with dot notation: acc1.balance.
这种绑定确保每个对象独立维护自己的状态,这是 OOP 的基本原则。使用点符号访问属性:acc1.balance。
4. Encapsulation and Information Hiding | 封装与信息隐藏
Encapsulation restricts direct access to an object’s internal state. Python doesn’t enforce strict private members, but conventions indicate non-public intent: a single underscore _ signals protected, while a double underscore __ triggers name mangling. You provide access through getter and setter methods, or via properties using the @property decorator, which allows controlled attribute access.
封装限制了对对象内部状态的直接访问。Python 不强制执行严格的私有成员,但惯例表明了非公开意图:单下划线 _ 表示受保护,双下划线 __ 会触发名称改写。通过 getter 和 setter 方法,或使用 @property 装饰器实现属性,从而提供控制访问。
| Convention | Meaning | Example |
| self._x | Protected (internal use) | self._score |
| self.__x | Private (name mangled to _Class__x) | self.__secret |
Encapsulation is vital for maintaining invariants—for example, ensuring a balance never goes negative without validation.
封装对于维持不变量至关重要——例如,确保余额未经验证不会变为负数。
5. Inheritance and Code Reusability | 继承与代码复用
Inheritance allows a new class (child) to derive attributes and methods from an existing class (parent). This promotes the ‘is-a’ relationship. Use the parent name inside parentheses during class definition: class SportsCar(Car). The child can override parent methods or add new ones. Superclass initialization is called via super().__init__() to avoid duplicating code.
继承允许新类(子类)从现有类(父类)派生属性和方法,这体现了“is-a”关系。在类定义中,将父类名称放在括号内:class SportsCar(Car)。子类可以重写父类方法或添加新方法。通过 super().__init__() 调用超类初始化,避免代码重复。
Inheritance builds hierarchies, making structures easier to visualise and reducing duplication. However, deep inheritance chains must be designed carefully to avoid fragility.
继承构建了层次结构,使结构更易可视化,并减少重复。但深度继承链需要精心设计,以避免脆弱性。
6. Polymorphism and Method Overriding | 多态与方法重写
Polymorphism means ‘many forms’. It allows objects of different classes to be treated through a common interface. A method defined in a parent can be redefined in a child to exhibit different behaviour. For example, a Shape parent class might define a draw() method overridden by Circle and Rectangle. Code that calls shape.draw() works regardless of the actual subclass.
多态意为“多种形态”。它允许不同类的对象通过通用接口进行处理。父类中定义的方法可在子类中重新定义,表现出不同行为。例如,Shape 父类可定义 draw() 方法,由 Circle 和 Rectangle 重写。调用 shape.draw() 的代码,无论实际子类是什么都能正常工作。
Dynamic polymorphism in Python is achieved naturally because the call is resolved at runtime based on the object’s type—a technique known as duck typing. This reduces rigid type checks and encourages flexible design.
Python 中的动态多态是自然实现的,因为调用在运行时根据对象类型解析——这种技术称为鸭子类型。这减少了严格的类型检查,鼓励灵活设计。
7. Composition and Aggregation | 组合与聚合
Instead of always using inheritance to model relationships, composition creates a ‘has-a’ link. An object contains instances of other classes, delegating tasks to them. For example, a Library class might contain a list of Book objects. Composition makes it easy to change behaviour at runtime by swapping components, and it often leads to simpler class hierarchies than deep inheritance.
与其总是使用继承来建模关系,组合体现的是“has-a”关联。一个对象包含其他类的实例,将任务委托给它们。例如,Library 类可包含 Book 对象的列表。组合便于在运行时通过交换组件来改变行为,而且通常比深度继承产生更简单的类结构。
Aggregation is a weaker form of composition where the contained object can exist independently of the container. Both patterns help achieve looser coupling, an important object-oriented design goal.
聚合是组合的较弱形式,被包含的对象可以独立于容器存在。这两种模式都有助于实现更松散的耦合,这是一个重要的面向对象设计目标。
8. Abstract Base Classes in Python | Python 中的抽象基类
An abstract base class (ABC) defines a template with methods that must be implemented by subclasses. In Python, you use the abc module and the @abstractmethod decorator. This enforces that any concrete subclass provides its own version of the method, avoiding incomplete implementations. For instance, an abstract Vehicle class with start_engine() as an abstract method ensures every vehicle type defines how it starts.
抽象基类(ABC)定义了一个模板,带有子类必须实现的方法。在 Python 中,使用 abc 模块和 @abstractmethod 装饰器。这会强制任何具体子类提供方法自身的版本,避免不完整的实现。例如,一个抽象的 Vehicle 类,将 start_engine() 作为抽象方法,可确保每种车辆类型都定义了启动方式。
ABCs cannot be instantiated directly; they serve as a contract. This concept appears in Edexcel pseudocode as well, where abstract classes are often used to express polymorphic behaviour in design questions.
ABC 不能直接实例化,它们作为一种契约。这一概念也出现在 Edexcel 伪代码中,在设计问题里常用抽象类表达多态行为。
9. Class Variables, Instance Variables and self | 类变量、实例变量与 self
Class variables are shared across all instances and are defined directly inside the class body (not under __init__). Instance variables are unique to each object. The keyword self binds the instance to the method, allowing access to both instance and class data. A common exam question asks you to distinguish between a class attribute like school_name and an instance attribute like student_id.
类变量在所有实例之间共享,直接定义在类体中(不在 __init__ 下)。实例变量对于每个对象是唯一的。关键字 self 将实例绑定到方法,允许访问实例和类的数据。常见的考题是让你区分像 school_name 这样的类属性和 student_id 这样的实例属性。
Student.school_name = ‘Edexcel Academy’ (class variable, one copy shared)
学生.school_name = ‘Edexcel Academy’ (类变量,多实例共享同一份)
Changing a class variable through the class name affects all instances, but if you assign via an instance, a new instance variable is created, shadowing the class variable temporarily—a subtle point worth remembering for debugging.
通过类名更改类变量会影响所有实例,但若通过实例赋值,则会创建一个新的实例变量,暂时遮盖类变量——这是在调试中值得记住的微妙之处。
10. OOP Design for a Real-World Scenario | 面向对象实际场景设计
Consider modelling a library system. You might define a Book class with attributes like ISBN, title, and a method check_out(). A Member class could hold personal details and a list of borrowed books. A Library class composes the collection of books and members. Polymorphism could surface with a MediaItem parent inherited by Book and DVD, each implementing a get_loan_period() method differently.
考虑建模一个图书馆系统。你可以定义一个 Book 类,属性包括 ISBN、title,以及方法 check_out()。Member 类可以保存个人详情和已借图书列表。Library 类则由书籍和成员集合组合而成。多态可以通过 MediaItem 父类体现,由 Book 和 DVD 继承,各自以不同方式实现 get_loan_period() 方法。
When tackling A-Level scenario-based questions, start by identifying nouns (potential classes) and verbs (potential methods). Sketching a class diagram can clarify associations before coding. This design-first approach aligns with Edexcel’s emphasis on computational thinking and planning.
在处理 A-Level 场景类问题时,先识别名词(潜在类)和动词(潜在方法)。在编码前绘制类图可以理清关联。这种设计为先的方法与 Edexcel 对计算思维和规划的强调相符。
11. Testing Object-Oriented Code | 面向对象代码测试
OOP code is usually tested by verifying that objects behave correctly in isolation and in collaboration. Unit tests using Python’s unittest module can check that methods return expected values and that state changes (like balance deductions) happen accurately. Mocking objects helps test interactions without relying on real external resources, such as databases or file systems.
OOP 代码通常通过验证对象在隔离和协作中行为正确来测试。使用 Python 的 unittest 模块进行单元测试可以检查方法是否返回预期值,以及状态变化(如余额扣除)是否准确。模拟对象有助于在不依赖真实外部资源(如数据库或文件系统)的情况下测试交互。
Testing inheritance hierarchies requires careful thought. When a subclass overrides a method, both the parent and child implementations might need separate tests. Writing testable code means embracing loose coupling and adhering to the principle of dependency injection where possible.
测试继承层次结构需要仔细考量。当子类重写方法时,父类和子类实现可能需要分别进行测试。编写可测试代码意味着尽可能采用松散耦合,并遵循依赖注入原则。
12. Exam Tips for Edexcel A-Level Programming | Edexcel A-Level 编程考试技巧
In Edexcel Paper 1 (Principles of Computer Science) and the on-screen programming paper, you may be asked to write or analyse OOP code. Key tips: always initialise instance variables in __init__; use self correctly and recognise that a method call like obj.action(x) translates internally to Class.action(obj, x). Be ready to identify advantages of OOP, such as reusability, easier maintenance, and modelling real-world entities.
在 Edexcel 试卷 1(计算机科学原理)和上机编程考试中,可能会要求编写或分析 OOP 代码。关键提示:务必在 __init__ 中初始化实例变量;正确使用 self,并认识到像 obj.action(x) 这样的方法调用在内部转换为 Class.action(obj, x)。准备识别 OOP 的优点,如可重用性、易于维护以及模拟真实世界实体。
Pseudocode questions may ask you to illustrate inheritance or polymorphism without writing perfect Python. Using clear class diagrams and annotations earns marks. When debugging provided code, check for common pitfalls: missing self, incorrect indentation, and attribute shadowing. Remember that OOP concepts appear across both computational thinking and practical programming questions, so solidify your understanding through consistent practice.
伪代码问题可能会要求你说明继承或多态,而不必写出完美 Python。使用清晰的类图和注释即可得分。调试给定代码时,检查常见陷阱:缺少 self、缩进错误以及属性遮盖。请记住,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课程辅导,国外大学本科硕士研究生博士课程论文辅导Cancel reply