📚 Object-Oriented Programming in Python for Edexcel A-Level | Edexcel A-Level 面向对象编程(Python)
Object-oriented programming (OOP) is a core paradigm in the Edexcel A-Level Computer Science specification, and it is often examined using Python. Understanding OOP allows you to model real-world entities, organise code into reusable components, and apply key principles like encapsulation, inheritance, and polymorphism. This article provides a thorough revision guide covering every essential OOP concept tested at A-Level, with clear explanations, Python examples, and exam-style insights to help you master Topic 4 (Programming) and related algorithmic thinking tasks.
面向对象编程 (OOP) 是 Edexcel A-Level 计算机科学课程的核心范式,考试中常以 Python 为载体进行考查。理解 OOP 能够让你对现实世界实体建模、将代码组织为可复用组件,并应用封装、继承、多态等关键原则。本文提供一份全面的复习指南,覆盖 A-Level 考试中每个重要的 OOP 概念,配以清晰的解释、Python 示例和应试视角,助你掌握专题 4(编程)及相关算法思维任务。
1. What Is Object-Oriented Programming? | 什么是面向对象编程?
Object-oriented programming organises code around objects rather than functions or logic. An object bundles data (attributes) and behaviour (methods) together. This paradigm mirrors how we perceive real-world entities: a ‘Car’ object has attributes like colour and speed, and methods like accelerate() and brake(). OOP promotes modularity, reusability, and easier maintenance, which is why it is a major part of the Edexcel A-Level syllabus.
面向对象编程以对象(而非函数或逻辑)为中心组织代码。一个对象将数据(属性)与行为(方法)捆绑在一起。这种范式贴合我们对现实世界实体的感知:“汽车”对象有颜色、速度等属性,以及加速、刹车等方法。OOP 提升了程序的模块化、可复用性与可维护性,因此成为 Edexcel A-Level 大纲的重要组成部分。
2. Classes and Objects | 类与对象
A class is a blueprint for creating objects. It defines the attributes and methods that its objects will have. An object is an instance of a class. For example, if Student is a class, then student1 = Student("Alice", 17) creates an object of that class. Each object gets its own copy of instance attributes but shares the method definitions. In Python, a class is defined using the class keyword.
类是创建对象的蓝图,定义了对象将拥有的属性和方法。对象是类的实例。例如,若 Student 是类,则 student1 = Student("Alice", 17) 就创建了该类的一个对象。每个对象拥有自己的实例属性副本,但共享方法定义。在 Python 中,类使用 class 关键字定义。
Exam questions may ask you to identify classes and objects from a scenario, draw UML class diagrams, or write Python code to instantiate objects. Always recognise that a class name is capitalised by convention and that calling the class as a function triggers the constructor.
考试题可能要求你从场景中识别类和对象、绘制 UML 类图,或编写 Python 代码实例化对象。请牢记:按惯例类名应大写,而像函数一样调用类会触发构造函数。
3. Attributes and Methods | 属性与方法
Attributes store an object’s state, while methods define its behaviours. Instance attributes are typically set inside the __init__ method using self. Methods are functions defined inside a class, and their first parameter is always self, which refers to the current instance. For example, a BankAccount class might have an attribute balance and a method deposit(amount).
属性存储对象的状态,方法定义对象的行为。实例属性通常在 __init__ 方法内通过 self 设置。方法是定义在类内部的函数,其第一个参数总是 self,指向当前实例。例如,BankAccount 类可能有属性 balance 和方法 deposit(amount)。
Distinguish between instance attributes (unique per object) and class attributes (shared across all instances). Class attributes are defined directly inside the class body and accessed via the class name. Edexcel examiners often test your ability to trace code that uses class attributes versus instance attributes.
要区分实例属性(每个对象唯一)与类属性(所有实例共享)。类属性直接定义在类体中,可通过类名访问。Edexcel 考官常考查追踪同时使用类属性与实例属性的代码的能力。
4. Encapsulation | 封装
Encapsulation is the bundling of data with the methods that operate on that data, and it restricts direct access to an object’s internal state. In Python, encapsulation is conventionally achieved by using a leading underscore (_protected) or double leading underscore (__private) to signal that attributes or methods are not part of the public API. Although Python does not enforce true privacy, the convention aids in writing robust code and is relevant to the Edexcel specification.
封装是将数据与操作数据的方法捆绑在一起,并限制对对象内部状态的直接访问。在 Python 中,封装通常通过前置单下划线 (_protected) 或双下划线 (__private) 来标记属性或方法不属于公共接口。尽管 Python 不实施真正的私有,但这种约定有助于编写健壮代码,且与 Edexcel 规格相关。
Accessor (getter) and mutator (setter) methods are typical OOP techniques to interact with encapsulated data. For instance, a get_balance() method can return the balance without exposing the internal attribute directly, allowing validation in setter methods.
访问器 (getter) 和修改器 (setter) 方法是与封装数据交互的典型 OOP 技术。例如,get_balance() 方法可以返回余额而不直接暴露内部属性,并可在 setter 方法中进行验证。
5. Inheritance | 继承
Inheritance allows a class (child) to derive attributes and methods from another class (parent). This promotes code reuse and establishes a hierarchical relationship. In Python, you specify the parent class in parentheses: class ElectricCar(Car):. The child class can override parent methods or add new ones. Inheritance is frequently tested in Edexcel Paper 2 where you may need to interpret or extend class hierarchies.
继承允许一个类(子类)从另一个类(父类)派生属性和方法。这促进了代码复用并建立了层次关系。在 Python 中,可在括号中指定父类:class ElectricCar(Car):。子类可以重写父类方法或新增方法。Edexcel Paper 2 常涉及继承,可能需要你解读或扩展类层次结构。
Python supports multiple inheritance, but A-Level questions usually focus on single inheritance. Use built-in super() to call the parent constructor, ensuring the parent’s initialisation logic executes. Remember the Liskov substitution principle: a child object should be usable wherever a parent object is expected.
Python 支持多重继承,但 A-Level 考试通常聚焦单继承。使用内置的 super() 调用父类构造函数,确保父类的初始化逻辑得以执行。记住里氏代换原则:在任何需要父类对象的地方都可以使用子类对象。
6. Polymorphism | 多态
Polymorphism means “many forms” and allows objects of different classes to respond to the same method call in their own way. This is achieved through method overriding and duck typing in Python. For example, both Dog and Cat can have a speak() method, and a loop iterating over a list of animals can call speak() without knowing their exact class. Edexcel questions often link polymorphism with inheritance and abstract classes.
多态意为“多种形态”,允许不同类的对象以自己的方式响应相同的方法调用。在 Python 中通过方法重写和鸭子类型实现。例如,Dog 和 Cat 都可以有 speak() 方法,而遍历动物列表的循环无需知道具体类就可以调用 speak()。Edexcel 考题常将多态与继承、抽象类联系起来。
Method overloading (same method name, different parameters) is not natively supported in Python in the same way as Java, but you can achieve similar effects using default arguments or *args. Polymorphism is a critical concept for modelling systems and designing maintainable software.
方法重载(同名方法、不同参数)在 Python 中不像 Java 那样原生支持,但可通过默认参数或 *args 达到类似效果。多态是系统建模和设计可维护软件的关键概念。
7. Constructors and the self Parameter | 构造函数与 self 参数
The constructor __init__ is a special method called automatically when a new object is created. It initialises the object’s attributes. In Python, __init__(self, ...) receives the freshly created instance as self. You must include self as the first parameter in all instance methods. Failure to use self correctly is a common mistake that Edexcel mark schemes highlight.
构造函数 __init__ 是在新对象创建时自动调用的特殊方法,用于初始化对象的属性。在 Python 中,__init__(self, ...) 将新创建实例作为 self 接收。所有实例方法都必须将 self 作为第一个参数。未能正确使用 self 是 Edexcel 评分标准常指出的常见错误。
Python also has a destructor __del__, which is rarely needed but may be referenced to explain resource deallocation. For A-Level, focus on writing and tracing __init__ logic accurately, including assigning attributes using self.attribute = value.
Python 还有一个析构函数 __del__,虽然很少需要,但可能用来解释资源释放。对于 A-Level,重点在于准确编写和追踪 __init__ 逻辑,包括使用 self.attribute = value 赋值属性。
8. Method Overriding and Super | 方法重写与 super 函数
Method overriding occurs when a child class provides a different implementation of a method that exists in the parent class. The child’s version replaces the parent’s for instances of that child. Use super().method() to call the parent version from within the overriding method, which preserves and extends existing behaviour. This is essential in exam scenarios that construct complex class hierarchies.
方法重写发生在子类提供了父类已有方法的不同实现时。对于子类的实例,子类的版本会取代父类的版本。使用 super().method() 可在重写方法内部调用父类版本,从而保留并扩展现有行为。这在构建复杂类层次结构的考试场景中至关重要。
Edexcel often provides incomplete Python code and asks you to complete a subclass by overriding a method while using super to avoid code duplication. Practice writing clear, concise overrides that respect the parent class contract.
Edexcel 常给出一段不完整的 Python 代码,要求你通过重写方法并使用 super 来完善子类,以避免代码重复。要多练习编写清晰、简洁的重写,同时遵守父类契约。
9. Access Modifiers in Python | Python 中的访问修饰符
Python does not have strict public/private keywords like Java, but naming conventions serve as access modifiers. A single underscore _name indicates “protected” – intended for internal use and accessible in subclasses. A double underscore __name triggers name mangling, making it harder to access from outside (becomes _ClassName__name). Edexcel expects you to know the convention and how it relates to encapsulation.
Python 没有像 Java 那样严格的 public/private 关键字,但命名约定起到访问修饰符的作用。单下划线 _name 表示“受保护”——供内部使用且可在子类中访问。双下划线 __name 触发命名改写,使其更难从外部访问(变为 _ClassName__name)。Edexcel 希望你了解这种约定及其与封装的关系。
In the exam, you may be asked to identify a potentially encapsulated attribute and suggest how to protect it. Use properties (@property) to define managed access to attributes, which aligns with the principle of encapsulation and is a popular Pythonic pattern.
考试中可能要求你识别某个可能封装的属性并建议如何保护它。可使用特性装饰器 (@property) 定义对属性的受控访问,这符合封装原则且是流行的 Pythonic 方式。
10. Static and Class Methods | 静态方法与类方法
While instance methods receive self, Python also supports static methods (@staticmethod) and class methods (@classmethod). A static method does not access the instance or class and behaves like a plain function belonging to the class’s namespace. A class method receives the class itself (cls) as the first parameter and can modify class state. A-Level candidates should recognise these and understand when to use them.
实例方法接收 self,而 Python 还支持静态方法 (@staticmethod) 和类方法 (@classmethod)。静态方法不访问实例或类,行为类似属于类命名空间的普通函数。类方法接收类 (cls) 作为第一个参数,可以修改类状态。A-Level 考生应能识别它们并理解其使用场景。
Class methods are often used as factory methods, providing alternative constructors. For instance, Person.from_birth_year() could calculate age and return a Person object. Edexcel questions may ask you to complete such factory methods, testing your understanding of OOP design.
类方法常用作工厂方法,提供替代的构造函数。例如,Person.from_birth_year() 可以计算年龄并返回一个 Person 对象。Edexcel 可能要求你完善这类工厂方法,以测试你对 OOP 设计的理解。
11. OOP Design Principles and Exam Practice | OOP 设计原则与考试练习
Beyond syntax, Edexcel tests your ability to apply OOP design principles: cohesion (how closely related the functions inside a class are), coupling (how dependent classes are on each other), and the SOLID principles. Aim for high cohesion and low coupling to produce maintainable code. Exam questions may present a class diagram and ask you to evaluate its design or suggest improvements.
除了语法,Edexcel 还测试你应用 OOP 设计原则的能力:内聚(类内部函数的相关程度)、耦合(类之间相互依赖的程度)以及 SOLID 原则。力求高内聚、低耦合以生产可维护代码。考题可能给出一个类图,要求你评估其设计或提出改进建议。
Practice past-paper questions that ask you to write a complete Python class from a specification, draw UML diagrams, and trace object interactions. Pay attention to correct use of self, proper constructor implementation, and the correct application of inheritance and polymorphism.
多练习历年试题,包括根据规格编写完整的 Python 类、绘制 UML 图以及追踪对象交互。注意正确使用 self、恰当的构造函数实现,以及继承和多态的正确应用。
| Concept | OOP Keyword | Python Syntax Example |
| Encapsulation | __private, _protected | self.__balance |
| Inheritance | class Child(Parent) | class Square(Rectangle) |
| Polymorphism | Overriding, duck typing | def area(): different in each class |
12. Common Mistakes and Final Tips | 常见错误与最终建议
Students often forget to include self in method signatures, leading to TypeError when calling the method. Another frequent slip is attempting to use private attributes directly from outside the class without getter methods, which breaks encapsulation. In trace questions, missing that a subclass constructor calls super().__init__ can cause wrong attribute values. Review these pitfalls carefully.
学生常忘记在方法签名中写 self,导致调用方法时抛出 TypeError。另一个常见疏漏是试图从类外部直接访问私有属性而不使用 getter 方法,这破坏了封装。在代码追踪题中,忽略了子类构造函数调用 super().__init__ 可能导致属性值错误。要仔细回顾这些陷阱。
For exam success, practise writing classes under timed conditions, always check that your code follows the specification’s naming conventions, and annotate your design decisions where appropriate. Remember that clean, well-structured OOP code earns marks for readability and maintainability, not just correctness.
为考试成功,请在限时条件下练习编写类,始终检查代码是否遵循规格的命名约定,并适当注释你的设计决策。记住,干净、结构良好的 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课程辅导,国外大学本科硕士研究生博士课程论文辅导