Tag: 编程

  • Object-Oriented Programming for A-Level Edexcel Computer Science | A-Level Edexcel 计算机科学面向对象编程

    📚 Object-Oriented Programming for A-Level Edexcel Computer Science | A-Level Edexcel 计算机科学面向对象编程

    Object-Oriented Programming (OOP) is a fundamental paradigm in the Edexcel A-Level Computer Science specification, especially for Paper 2 and the programming project. Understanding classes, objects, inheritance and polymorphism is essential for designing robust, reusable code.

    面向对象编程 (OOP) 是 Edexcel A-Level 计算机科学课程(尤其是 Paper 2 和编程项目)的基本范式。理解类、对象、继承和多态对于设计健壮、可复用的代码至关重要。

    1. OOP Fundamentals | 面向对象编程基础

    OOP models real-world entities as objects that contain both data (attributes) and behaviour (methods). This contrasts with procedural programming, where data and functions are separate.

    面向对象编程将现实世界的实体建模为包含数据(属性)和行为(方法)的对象。这与过程式编程形成对比,后者将数据与函数分离。

    The four pillars of OOP are encapsulation, abstraction, inheritance, and polymorphism. In Edexcel exams, you must be able to explain each and identify them in code snippets.

    OOP 的四大支柱是封装、抽象、继承和多态。在 Edexcel 考试中,你必须能够解释每一项,并在代码片段中识别它们。

    A class is a blueprint for creating objects; an object is an instance of a class. For example, a “Car” class defines attributes like colour and speed, and methods like accelerate() and brake().

    类是创建对象的蓝图;对象是类的实例。例如,”Car” 类定义了颜色和速度等属性,以及 accelerate() 和 brake() 等方法。


    2. Defining Classes and Instantiating Objects | 定义类与实例化对象

    In Python (frequently used for Edexcel programming), a class is defined using the class keyword. The constructor method __init__ initialises object attributes. Objects are created by calling the class name with arguments.

    在 Python(Edexcel 编程常用语言)中,使用 class 关键字定义类。构造方法 __init__ 用于初始化对象属性。通过用参数调用类名来创建对象。

    Example: my_car = Car("red", 0) creates an instance of the Car class with the colour “red” and initial speed 0. Each object maintains its own state.

    示例:my_car = Car("red", 0) 创建了一个 Car 类的实例,颜色为 “red”,初始速度为 0。每个对象都维护着自己的状态。

    You must be comfortable with UML notation for classes, which Edexcel may ask you to interpret or draw in Paper 2. A class box shows the class name, attributes, and methods.

    你必须熟悉类的 UML 表示法,Edexcel 可能在 Paper 2 中要求解释或绘制类图。类框显示类名、属性和方法。


    3. Attributes and Methods | 属性与方法

    Attributes represent the data stored within an object. They can be public, protected (prefixed with a single underscore _ ), or private (double underscore __ ) by convention in Python.

    属性代表存储在对象中的数据。在 Python 中,按照约定,属性可以是公有的、受保护的(单下划线 _ 前缀)或私有的(双下划线 __ 前缀)。

    Methods define the behaviours of an object. They are functions defined inside a class and always take self as the first parameter, referring to the current instance.

    方法定义了对象的行为。它们是类内部定义的函数,并始终以 self 作为第一个参数,指代当前实例。

    Getter and setter methods control access to attributes safely, which is a key aspect of encapsulation. Edexcel pseudocode may use getAge() and setAge() explicitly.

    Getter 和 setter 方法是封装的关键方面,用于安全地控制对属性的访问。Edexcel 伪代码可能显式使用 getAge()setAge()


    4. Encapsulation and Data Hiding | 封装与数据隐藏

    Encapsulation bundles data (attributes) with the methods that operate on that data, restricting direct access from outside the class. It promotes modularity and prevents accidental interference.

    封装将数据(属性)与操作数据的方法捆绑在一起,限制从类外部直接访问。它提升了模块性并防止意外干扰。

    In exam answers, you should stress that encapsulation hides the internal state and requires interaction through a public interface. This makes code easier to debug and maintain.

    在考试答案中,你应强调封装隐藏了内部状态,并要求通过公共接口进行交互。这使得代码更易于调试和维护。

    Private attributes (e.g., self.__balance) cannot be accessed directly from outside the class; a public method such as deposit(amount) must be used. This ensures data integrity.

    私有属性(如 self.__balance)不能从类外部直接访问;必须使用诸如 deposit(amount) 的公共方法。这确保了数据的完整性。


    5. Inheritance: Extending Functionality | 继承:扩展功能

    Inheritance allows a new child class (subclass) to derive attributes and methods from an existing parent class (superclass). This promotes code reuse and establishes a hierarchical relationship.

    继承允许新的子类从现有父类(超类)派生属性和方法。这促进了代码复用并建立了层次关系。

    Example: A “Dog” class inherits from an “Animal” class and adds a bark() method. The keyword class Dog(Animal): indicates this relationship in Python.

    示例:”Dog” 类从 “Animal” 类继承,并添加了 bark() 方法。Python 中使用 class Dog(Animal): 关键字表明这种关系。

    In Edexcel exams, you may see UML arrows pointing from subclass to superclass with an empty triangle. You must be able to identify overridden methods and the super() call.

    在 Edexcel 考试中,你可能会看到带有空心三角箭头从子类指向父类的 UML 图。你必须能够识别重写的方法和 super() 调用。


    6. Polymorphism: Many Forms | 多态:多种形态

    Polymorphism means “many forms” and allows objects of different classes to be treated as objects of a common superclass. The most common form is method overriding.

    多态意味着 “多种形态”,允许将不同类的对象视为共同超类的对象。最常见的形式是方法重写。

    If both Cat and Dog classes inherit from Animal and override a speak() method, a loop through a list of Animal objects can call speak() and produce a different sound for each.

    如果 Cat 和 Dog 类都继承自 Animal 并重写了 speak() 方法,则循环遍历 Animal 对象列表时调用 speak(),会为每个对象产生不同的声音。

    This is a key concept for Edexcel: you need to explain how polymorphism simplifies code by allowing the same interface to be used for different underlying data types.

    这是 Edexcel 的关键概念:你需要解释多态如何通过允许对不同的底层数据类型使用相同的接口来简化代码。


    7. Constructors and the __init__ Method | 构造方法与 __init__ 方法

    A constructor is a special method invoked automatically when an object is instantiated. In Python, __init__(self) serves as the constructor and initialises the object’s state.

    构造方法是一种特殊方法,在实例化对象时自动调用。在 Python 中,__init__(self) 充当构造方法,并初始化对象的状态。

    It is possible to define multiple constructors using default parameters. Edexcel pseudocode often uses the keyword NEW to create an object and implicitly call its constructor.

    可以使用默认参数定义多个构造方法。Edexcel 伪代码通常使用关键字 NEW 来创建对象并隐式调用其构造方法。

    Destructors (using __del__) are rarely required in Python due to automatic garbage collection, but you should know they exist for releasing resources in other OOP languages.

    由于 Python 有自动垃圾回收,析构方法(使用 __del__)很少需要,但你应该知道它们在其他 OOP 语言中用于释放资源。


    8. Access Modifiers and Naming Conventions | 访问修饰符与命名约定

    Access modifiers control the visibility of class members. Python does not enforce strict private/public, but uses conventions: single underscore for protected, double underscore for name mangling.

    访问修饰符控制类成员的可见性。Python 不强制执行严格的私有/公有,但使用约定:单下划线表示受保护,双下划线进行名称修饰。

    In your exam, when asked to “identify a private attribute”, look for the double underscore prefix. Understand that encapsulation is conceptually about restricting access, not a language rule.

    在考试中,当被问到 “识别一个私有属性” 时,请查找双下划线前缀。要理解封装在概念上是关于限制访问,而非语言规则。

    An Edexcel mark scheme may accept “private variables should not be accessible directly, only through public methods” as a correct explanation of encapsulation.

    Edexcel 的评分方案可能接受 “私有变量不应直接访问,只能通过公共方法访问” 作为封装的正确解释。


    9. UML Class Diagrams in Edexcel | Edexcel 中的 UML 类图

    Unified Modelling Language (UML) class diagrams are frequently tested. A class is drawn as a rectangle split into three sections: name, attributes, and methods.

    统一建模语言 (UML) 类图经常被考查。类被绘制成一个矩形,分为三个部分:名称、属性和方法。

    Visibility markers are placed before member names: ‘+’ for public, ‘-‘ for private, ‘#’ for protected. You must be able to read and draw these diagrams accurately.

    可见性标记放在成员名称之前:’+’ 表示公有,’-‘ 表示私有,’#’ 表示受保护。你必须能够准确地阅读和绘制这些图表。

    Associations, aggregation (empty diamond), and composition (filled diamond) show relationships. Inheritance is shown with an empty triangle arrow. Practise linking classes correctly.

    关联、聚合(空心菱形)和组合(实心菱形)表示关系。继承用空心三角箭头表示。练习正确链接类。


    10. OOP vs Procedural Programming | 面向对象与过程式编程对比

    Procedural programming organises code into functions that act on data, whereas OOP groups data and functions into objects. OOP makes it easier to manage large, complex systems.

    过程式编程将代码组织为操作数据的函数,而 OOP 将数据和函数分组到对象中。OOP 使得管理大型复杂系统更加容易。

    Key differences for Edexcel: OOP promotes reusability through inheritance, supports encapsulation for security, and models real-world entities more naturally.

    Edexcel 考察的关键区别:OOP 通过继承促进复用性,支持封装以确保安全,并且更自然地建模现实世界实体。

    However, OOP can have a steeper learning curve and may introduce unnecessary overhead for small scripts. Expect a compare/contrast question in Section B of Paper 2.

    然而,OOP 的学习曲线可能更陡峭,对于小脚本可能引入不必要的开销。预计 Paper 2 B 部分会出现比较/对比题。


    11. Exam-Style Questions and Tips | 考试风格问题与技巧

    Common questions ask you to write a class definition from a scenario, identify OOP features in a given code, or complete a UML diagram. Always use correct indentation and naming.

    常见问题要求你根据情景编写类定义,识别给定代码中的 OOP 特性,或完成 UML 图。始终使用正确的缩进和命名。

    When asked “explain the advantage of using inheritance”, mention code reuse, reduced duplication, and easier maintenance. Provide a short example to support your answer.

    当被问到 “解释使用继承的优势” 时,要提到代码复用、减少重复和更易于维护。提供一个简短的示例来支持你的答案。

    Watch out for trick questions about polymorphism: an overridden method has the same signature but different behaviour. Reference the parent class with super() if needed.

    注意关于多态的陷阱问题:重写的方法具有相同的签名但不同的行为。如果需要在子类中引用父类的方法,使用 super()。


    12. Summary and Key Takeaways | 总结与关键要点

    Mastering OOP means understanding classes, objects, encapsulation, inheritance, and polymorphism. These concepts form the backbone of modern software design and are heavily assessed.

    掌握面向对象编程意味着理解类、对象、封装、继承和多态。这些概念构成了现代软件设计的骨干,并且是重点考查内容。

    Practise by creating small programs, drawing UML diagrams, and explaining OOP terms using precise technical language. This will prepare you for both the written exam and NEA project.

    通过创建小程序、绘制 UML 图并使用精确的技术语言解释 OOP 术语来进行练习。这将为你准备笔试和 NEA 项目。

    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Combined Programming Operations: Merging Sorting and Searching | 编程中的组合操作:排序与搜索的融合

    📚 Combined Programming Operations: Merging Sorting and Searching | 编程中的组合操作:排序与搜索的融合

    In A-Level Programming, combining fundamental algorithms such as sorting and searching is a key skill for solving complex problems efficiently.

    在 A-Level 编程中,将排序和搜索等基本算法结合起来是高效解决复杂问题的关键技能。

    This article explores how different operations can be integrated to optimise performance, with practical examples aligned to the Edexcel specification.

    本文探讨了如何整合不同操作以优化性能,并提供符合 Edexcel 考试大纲的实例。

    1. The Role of Sorting in Search Efficiency | 排序对搜索效率的作用

    When a dataset is unsorted, searching for an item typically requires a linear scan, which has O(n) time complexity.

    当数据集未排序时,搜索项目通常需要线性扫描,时间复杂度为 O(n)。

    By first sorting the data using an efficient algorithm, we can then apply binary search to achieve O(log₂ n) lookups.

    通过首先使用高效算法对数据进行排序,我们可以应用二分搜索实现 O(log₂ n) 的查找。

    However, the initial sorting step itself has a cost, so the combined operation must be evaluated for overall efficiency.

    然而初始排序步骤本身也有开销,因此必须评估组合操作的总体效率。

    For static datasets queried many times, the one-time sorting cost is justified by subsequent fast searches.

    对于多次查询的静态数据集,一次性排序开销可通过后续快速搜索来补偿。


    2. Linear Search and Simple Sorts | 线性搜索与简单排序

    Linear search examines each element sequentially, making it simple but inefficient for large collections.

    线性搜索按顺序检查每个元素,虽然简单但对大型集合效率低下。

    Bubble sort, a simple O(n²) algorithm, can be used to sort data before applying linear search, but the total cost remains O(n²).

    冒泡排序是一种简单的 O(n²) 算法,可用于在线性搜索前排序数据,但总开销仍为 O(n²)。

    In exam scenarios, you may be asked to combine linear search with insertion sort and analyse the resulting complexity.

    在考试情境中,你可能需要将线性搜索与插入排序结合并分析最终的复杂度。

    A better approach for small datasets is to use insertion sort and then linear search if no better alternative exists.

    处理小型数据集的一个更好方法是若无更优选择,则使用插入排序再进行线性搜索。


    3. Binary Search and Quicksort | 二分搜索与快速排序

    Binary search requires a sorted array and operates by repeatedly dividing the search interval in half.

    二分搜索需要有序数组,并通过反复将搜索区间减半来操作。

    Quicksort is a divide-and-conquer algorithm with average complexity O(n log₂ n), making it a popular choice for pre-sorting.

    快速排序是一种分治算法,平均复杂度为 O(n log₂ n),因此是预排序的常用选择。

    The combination of quicksort and binary search yields O(n log₂ n) preprocessing plus O(log₂ n) per query.

    快速排序与二分搜索结合的方案产生 O(n log₂ n) 预处理时间以及每次查询 O(log₂ n) 时间。

    Note that in the worst case, quicksort degrades to O(n²) if the pivot selection is poor.

    注意,最坏情况下如果枢轴选择不当,快速排序会退化到 O(n²)。

    Edexcel exams often test your ability to trace these combined algorithms on small arrays.

    Edexcel 考试经常考查你在小型数组上追踪这些组合算法的能力。


    4. Hash Tables and Pre-sorting | 哈希表与预排序

    A hash table can provide average O(1) search time without sorting, but it requires extra memory.

    哈希表无需排序即可提供平均 O(1) 的搜索时间,但需要额外内存。

    If data must also be retrieved in sorted order, a hash table alone is insufficient; we can combine it with a sorted array or balanced tree.

    如果数据还必须按排序顺序检索,仅有哈希表是不够的;我们可以将其与有序数组或平衡树结合使用。

    One common pattern is to insert items into a hash table for quick existence checks and maintain a parallel sorted list for range queries.

    一种常见模式是将项目插入哈希表以快速检查存在性,并维护一个平行的有序列表以进行范围查询。

    This hybrid approach balances insertion speed and ordered retrieval, a theme examined in A-Level programming tasks.

    这种混合方法平衡了插入速度与有序检索,是 A-Level 编程任务中考查的主题。


    5. Tree Structures and Search Operations | 树结构与搜索操作

    Binary search trees (BSTs) inherently support efficient searching, insertion, and deletion with average O(log₂ n) time.

    二叉搜索树 (BST) 天然支持搜索、插入和删除操作,平均时间为 O(log₂ n)。

    To keep the tree balanced, self-balancing variants like AVL trees are used in combined operation scenarios.

    为了保持树的平衡,在组合操作场景中使用了 AVL 树等自平衡变体。

    Traversals such as inorder can output sorted data, effectively combining tree construction and sorting.

    中序遍历等遍历方法可以输出排序后的数据,有效地将树的构建与排序结合了起来。

    When implementing a dictionary with both lookup and range search, a BST or B-tree is often preferred.

    在实现同时需要查找和范围搜索的字典时,通常首选 BST 或 B 树。


    6. Priority Queues and Heaps | 优先队列与堆

    A heap is a complete binary tree used to implement a priority queue, providing O(log₂ n) insertion and O(1) peek at the extremum.

    堆是一种完全二叉树,用于实现优先队列,提供 O(log₂ n) 插入和 O(1) 极值查看。

    Heap sort uses a max-heap to sort an array in O(n log₂ n) time, combining heap operations with the sorting problem.

    堆排序使用最大堆在 O(n log₂ n) 时间内对数组排序,将堆操作与排序问题相结合。

    In task scheduling algorithms, a priority queue selects the next task, while sorting initial tasks by deadline may be a preprocessing step.

    在任务调度算法中,优先队列选择下一个任务,而按截止时间对初始任务排序可能是一个

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming Concepts | 面向对象编程概念

    📚 Object-Oriented Programming Concepts | 面向对象编程概念

    Object-Oriented Programming (OOP) is a fundamental programming paradigm required for the Edexcel A-Level Computer Science specification. This article revisits the core OOP principles, provides pseudocode and real-world analogies, and explains how to recognise and apply encapsulation, inheritance, polymorphism, and abstraction in examination contexts.

    面向对象编程(OOP)是爱德思A-Level计算机科学课程要求掌握的一个基本编程范式。本文重温核心的OOP原则,提供伪代码和现实世界类比,并解释如何在考试情境中识别与运用封装、继承、多态与抽象。

    1. The Need for Programming Paradigms | 编程范式的必要性

    A programming paradigm is a style or way of programming. The two main paradigms assessed by Edexcel are procedural and object-oriented. Understanding the difference helps you choose the right approach for a given problem, and it is often examined in long-answer questions.

    编程范式是一种编程风格或方式。爱德思考察的两种主要范式是面向过程与面向对象。理解两者的区别有助于为特定问题选择合适的方法,这常常在长篇论述题中出现。

    Procedural programming breaks a problem into a sequence of instructions that operate on data, typically using functions and global variables. In contrast, OOP bundles data and the operations that act on that data into objects, promoting modularity and reuse.

    面向过程编程将问题分解为一系列操作数据的指令,通常使用函数和全局变量。相反,OOP将数据和对数据的操作捆绑成对象,从而促进模块化和重用。


    2. What Is Object-Oriented Programming? | 什么是面向对象编程?

    Object-Oriented Programming models real-world entities as objects that contain both data (attributes) and behaviours (methods). A program built using OOP is a collection of interacting objects rather than a list of instructions.

    面向对象编程把现实世界实体建模为对象,对象包含数据(属性)和行为(方法)。一个使用OOP构建的程序是一组相互协作的对象,而不是一系列指令。

    The key idea is that objects communicate by sending messages, often implemented as method calls. For the Edexcel specification, you need to interpret and write pseudocode that defines classes and creates objects.

    关键思想是对象通过发送消息进行通信,通常实现为方法调用。根据爱德思大纲,你需要能读懂并编写定义类和创建对象的伪代码。


    3. Classes and Objects | 类与对象

    A class is a blueprint or template that defines the attributes and methods common to all objects of a certain kind. An object is an instance of a class. You can create many objects from a single class, each with its own attribute values.

    类是定义某一类对象共有属性和方法的蓝图或模板。对象是类的实例。你可以从一个类创建多个对象,每个对象具有各自的属性值。

    In Edexcel pseudocode, a class definition often begins with the CLASS keyword, and an object is instantiated using NEW. For example:

    在爱德思伪代码中,类定义通常以CLASS关键字开头,对象用NEW实例化。例如:

    CLASS Car
      PRIVATE colour: STRING
      PRIVATE speed: INTEGER
      PUBLIC PROCEDURE accelerate(amount)
        speed = speed + amount
      ENDPROCEDURE
    ENDCLASS
    myCar = NEW Car

    Here, ‘Car’ is the class and ‘myCar’ is an object of type Car. The attributes ‘colour’ and ‘speed’ store state, and ‘accelerate’ is a method.

    此处’Car’是类,’myCar’是Car类型的对象。属性’colour’和’speed’存储状态,’accelerate’是方法。


    4. Attributes and Methods | 属性与方法

    Attributes are the data variables stored inside an object. They are often declared with a visibility modifier such as PRIVATE or PUBLIC. Methods are the procedures or functions defined inside a class that operate on the object’s attributes.

    属性是存储在对象内部的数据变量。它们通常用可见性修饰符(如PRIVATE或PUBLIC)声明。方法是在类内部定义的、操作对象属性的过程或函数。

    In Edexcel pseudocode, you must be able to identify getter and setter methods that provide controlled access to private attributes. These are sometimes called accessor and mutator methods, and they are a key part of encapsulation.

    在爱德思伪代码中,你必须能识别提供对私有属性受控访问的getter和setter方法。这些方法有时被称为访问器和修改器,是封装的关键部分。


    5. Encapsulation and Data Hiding | 封装与数据隐藏

    Encapsulation means bundling attributes and methods into a single unit (the class) and restricting direct access to some of the object’s components. This is achieved by declaring attributes as PRIVATE and providing PUBLIC methods to interact with them safely.

    封装意味着将属性和方法捆绑到一个单元(类)中,并限制对对象某些组成部分的直接访问。这通过将属性声明为PRIVATE并提供PUBLIC方法与之安全交互来实现。

    Encapsulation protects data from accidental corruption by outside code. For example, a setter method can validate new values before updating the attribute. Edexcel often asks you to explain why encapsulation is important for maintainability and security.

    封装保护数据免受外部代码意外破坏。例如,setter方法可以在更新属性之前验证新值。爱德思常要求解释封装对可维护性和安全性的重要性。


    6. Inheritance | 继承

    Inheritance allows a new class (subclass or child) to take on the attributes and methods of an existing class (superclass or parent). The subclass can then add its own unique features or override inherited methods to alter behaviour.

    继承允许一个新类(子类)继承已有类(父类)的属性和方法。子类随后可以添加自己的特有功能,或重写继承的方法以改变行为。

    In Edexcel pseudocode, inheritance is indicated using the INHERITS keyword. This models ‘IS-A’ relationships; for example, a Dog ‘is a’ Animal. Inheritance promotes code reuse and supports polymorphism.

    在爱德思伪代码中,继承用INHERITS关键字表示。这模拟了”是一种”关系;例如,Dog是一种Animal。继承促进代码复用并支持多态。

    CLASS Dog INHERITS Animal
      PUBLIC PROCEDURE bark()
        OUTPUT ‘Woof!’
      ENDPROCEDURE
    ENDCLASS


    7. Polymorphism | 多态

    Polymorphism means ‘many forms’. It allows objects of different classes to be treated as objects of a common superclass. The most common form is method overriding, where a subclass provides its own implementation of a method already defined in the parent class.

    多态意为”多种形态”。它允许不同类的对象被当作共同父类的对象来处理。最常见的形式是方法重写,即子类提供已经在父类中定义的方法的自身实现。

    For example, a parent class Shape may define a draw() method, while subclasses Circle and Rectangle each implement draw() differently. An array of type Shape can hold objects of any subclass, and calling draw() will invoke the correct version dynamically.

    例如,父类Shape可以定义draw()方法,而子类Circle和Rectangle各自以不同方式实现draw()。一个Shape类型的数组可以存放任何子类的对象,调用draw()时将动态调用正确版本。

    Edexcel pseudocode does not typically test dynamic dispatch explicitly, but you should understand the concept and be able to identify scenarios where polymorphism is used.

    爱德思伪代码通常不会明确考查动态分派,但你应该理解该概念,并能识别使用多态的场景。


    8. Abstraction | 抽象

    Abstraction simplifies complex reality by modelling classes appropriate to the problem and ignoring irrelevant detail. In OOP, abstract classes and interfaces define a contract for subclasses without providing a complete implementation.

    抽象通过构建适合问题域的类并忽略无关细节来简化复杂现实。在OOP中,抽象类和接口为子类定义了规约而不提供完整实现。

    An abstract class may contain one or more abstract methods that have no body. Subclasses must provide concrete implementations. This enforces a common interface while allowing flexibility, which is central to designing robust systems.

    抽象类可包含一个或多个没有方法体的抽象方法。子类必须提供具体实现。这在允许灵活性的同时强制统一接口,是设计稳健系统的核心。


    9. Constructors and Destructors | 构造函数与析构函数

    A constructor is a special method that runs automatically when an object is instantiated. It typically initialises attributes to valid default values. In Edexcel pseudocode, a constructor is written as a PUBLIC PROCEDURE with the name NEW.

    构造函数是一种特殊方法,在对象实例化时自动运行。它通常将属性初始化为有效的默认值。在爱德思伪代码中,构造函数写作名为NEW的PUBLIC PROCEDURE。

    A destructor is rarely required in modern languages with automatic memory management, but some exam questions may reference the concept. It is used to free resources before an object is destroyed.

    在现代带有自动内存管理的语言中很少需要析构函数,但有些考题可能提及该概念。它用于在对象销毁前释放资源。


    10. OOP in Practice: Pseudocode Example | OOP实践:伪代码示例

    Below is a complete pseudocode example that demonstrates encapsulation, inheritance, and polymorphism using a library system.

    以下是一个完整的伪代码示例,用一个图书馆系统演示封装、继承和多态。

    CLASS Member
      PRIVATE name: STRING
      PRIVATE memberID: STRING
      PUBLIC PROCEDURE NEW(n, id)
        name = n
        memberID = id
      ENDPROCEDURE
      PUBLIC FUNCTION getName() RETURNS STRING
        RETURN name
      ENDFUNCTION
    ENDCLASS

    CLASS Student INHERITS Member
      PRIVATE grade: INTEGER
      PUBLIC PROCEDURE NEW(n, id, g)
        super.NEW(n, id)
        grade = g
      ENDPROCEDURE
      PUBLIC FUNCTION getStatus() RETURNS STRING
        RETURN ‘Student in grade ‘ + STRING(grade)
      ENDFUNCTION
    ENDCLASS

    s = NEW Student(‘Alice’, ‘M001’, 12)
    OUTPUT s.getName()
    OUTPUT s.getStatus()

    The example shows how the Student subclass reuses the Member constructor via super.NEW and adds grade-specific behaviour. This encourages reuse and a logical class hierarchy.

    该示例展示Student子类如何通过super.NEW重用Member构造函数,并添加年级特定行为。这鼓励了复用和合理的类层次结构。


    11. Advantages and Disadvantages of OOP | 面向对象编程的优缺点

    Advantages / 优点 Disadvantages / 缺点
    Promotes code reuse through inheritance and composition Can be more complex to design initially
    Encapsulation improves security and maintainability May lead to large, deeply nested class hierarchies
    Polymorphism allows flexible and scalable systems Execution can be slower due to dynamic dispatch overhead
    Maps well to real-world modelling Not all problems suit an object-oriented approach

    Table: Key advantages and disadvantages of OOP.

    表:面向对象编程的主要优缺点。


    12. Edexcel Exam Tips | 爱德思考试技巧

    When answering OOP questions, always use the correct Edexcel pseudocode syntax. State visibility modifiers (PRIVATE/PUBLIC), indicate INHERITS where appropriate, and label constructors as NEW. If a question asks for ‘explain encapsulation’, describe the bundling of data and methods and the use of public getters/setters to protect private attributes.

    在回答OOP问题时,始终使用正确的爱德思伪代码语法。写出可见性修饰符(PRIVATE/PUBLIC),适当的地方标明INHERITS,并将构造函数标记为NEW。如果题目要求”解释封装”,描述数据和方法捆绑以及使用公共getter/setter保护私有属性。

    For comparison questions contrasting procedural and OOP, structure your answer around state management (global vs encapsulated), code organisation (function-based vs object-based), and reusability. Marks are awarded for precise use of terminology such as ‘instantiation’, ‘attribute’, ‘method’, and ‘hierarchy’.

    在对比面向过程与OOP的题目中,围绕状态管理(全局 vs 封装)、代码组织(基于函数 vs 基于对象)以及可复用性组织答案。使用”实例化”、”属性”、”方法”和”层次结构”等准确术语可以得分。

    Practice writing short pseudocode snippets that declare a class with at least one private attribute and a public method to show controlled access. This is a common style of question on Paper 1.

    练习编写简短的伪代码片段,声明一个至少包含一个私有属性和一个公共方法的类,以展示受控访问。这是试卷1中的常见题型。

    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Pearson ActiveLearn Programming Resources for Edexcel A-Level | Pearson ActiveLearn 为 Edexcel A-Level 提供的编程资源

    📚 Pearson ActiveLearn Programming Resources for Edexcel A-Level | Pearson ActiveLearn 为 Edexcel A-Level 提供的编程资源

    Pearson ActiveLearn provides a comprehensive digital learning environment for Edexcel A-Level Computer Science, offering interactive programming tasks, automated assessment, and scaffolded support that helps students master computational thinking and coding skills. This article explores the key features, learning structure, and best practices for making the most of the platform when preparing for the Edexcel A-Level programming components.

    Pearson ActiveLearn 为 Edexcel A-Level 计算机科学提供了一个完善的数字学习环境,提供交互式编程任务、自动评估和支架式支持,帮助学生掌握计算思维和编码技能。本文探讨了该平台的主要功能、学习结构以及最佳实践,以便在备考 Edexcel A-Level 编程部分时最大化利用平台资源。

    1. The ActiveLearn Programming Environment | ActiveLearn 编程环境

    Pearson ActiveLearn’s programming resources are embedded within an online workspace that mirrors a real‑world integrated development environment (IDE). Students can write, run, and debug code directly in the browser, with no additional software installation required. The environment supports Python, which is the primary language used in the Edexcel specification, and includes syntax highlighting, line numbering, and an output console.

    Pearson ActiveLearn 的编程资源内嵌在一个模拟真实集成开发环境 (IDE) 的在线工作区中。学生可以直接在浏览器中编写、运行和调试代码,无需安装额外软件。该环境支持 Python(Edexcel 考纲规定的主要语言),并提供语法高亮、行号和输出控制台。

    Each programming activity is linked to a specific topic within the Edexcel syllabus, such as algorithms, data structures, or object‑oriented programming. The platform saves student progress automatically, allowing learners to resume work from any device. Teachers can also access a dashboard to monitor completion rates and common errors.

    每个编程活动都与 Edexcel 大纲中的特定主题相关联,例如算法、数据结构或面向对象编程。平台会自动保存学生的进度,使学习者可以从任何设备继续学习。教师还可以访问仪表板来监控完成率和常见错误。


    2. Syllabus‑Aligned Programming Tasks | 与考纲一致的编程任务

    The ActiveLearn programming modules are organised according to the Edexcel A-Level specification (9EN0). Key areas covered include: data types and structures, iteration and selection, file handling, searching and sorting algorithms, recursion, and the development of graphical user interfaces. Each task includes a clear statement of the learning objectives and links to the relevant specification points.

    ActiveLearn 编程模块根据 Edexcel A-Level 考纲 (9EN0) 进行组织。涵盖的关键领域包括:数据类型与结构、迭代与选择、文件处理、搜索与排序算法、递归以及图形用户界面的开发。每项任务都包含明确的学习目标陈述和相关考纲点的链接。

    For example, a task on linear search might require students to implement the algorithm, test it with a range of data, and then analyse its time complexity. The task is broken down into smaller steps, with hints and partial code provided when students struggle. This scaffolding ensures that even less confident programmers can make steady progress.

    例如,关于线性搜索的任务可能要求学生实现该算法,用一系列数据进行测试,然后分析其时间复杂度。任务被分解为更小的步骤,当学生遇到困难时会提供提示和部分代码。这种支架式教学确保了即使不太自信的编程者也能稳步前进。


    3. Automated Feedback and Marking | 自动反馈与评分

    One of the most powerful features of the ActiveLearn programming resources is immediate automated feedback. When a student runs their code, the platform checks the output against expected results. If there is a mismatch, the system provides targeted error messages and hints on how to correct logical or syntactical mistakes. This reduces dependency on teacher intervention and encourages independent debugging.

    ActiveLearn 编程资源最强大的功能之一是即时自动反馈。当学生运行代码时,平台会根据预期结果检查输出。如果存在不匹配,系统会提供有针对性的错误信息以及如何纠正逻辑或语法错误的提示。这减少了对教师干预的依赖,并鼓励学生自主调试。

    The marking system also assesses code quality, including the use of meaningful variable names, appropriate comments, and efficient algorithms. Marks are awarded not only for correct output but also for the programming approach, reinforcing good coding practices required in the non‑exam assessment (NEA).

    评分系统还会评估代码质量,包括使用有意义的变量名、恰当的注释和高效的算法。得分不仅取决于正确的输出,还取决于编程方法,这强化了非考试评估 (NEA) 中要求的良好编码习惯。


    4. Interactive Challenges and Extension Tasks | 交互式挑战与拓展任务

    Beyond the core exercises, ActiveLearn includes a bank of extension challenges designed to stretch more able students. These challenges often integrate multiple programming concepts, such as combining file I/O with data validation and sorting to create a simple database application. Extension tasks are labelled with difficulty levels and estimated completion times.

    除了核心练习之外,ActiveLearn 还包含一系列拓展挑战,旨在提高能力较强的学生。这些挑战通常整合了多个编程概念,例如将文件输入输出与数据验证和排序相结合,创建一个简单的数据库应用程序。拓展任务标注了难度级别和预计完成时间。

    Students can also attempt contest‑style problems that mirror the problem‑solving section of the Edexcel A-Level exam paper. These problems require analytical thinking and the application of computational methods, helping to build confidence for the externally assessed written examination (Paper 1: Principles of Computer Science).

    学生还可以尝试竞赛风格的问题,这些问题模拟了 Edexcel A-Level 考试试卷中的问题解决部分。这些问题需要分析性思维和计算方法的运用,有助于为外部评估的书面考试(试卷 1:计算机科学原理)建立信心。


    5. Supporting Theory with Practical Programming | 用实践编程巩固理论

    In the Edexcel specification, programming is closely integrated with theoretical concepts such as abstraction, decomposition, and algorithmic efficiency. ActiveLearn reinforces this link by embedding short theory quizzes before or after practical tasks. For instance, before implementing a bubble sort, students might be asked to explain why it has O(n²) time complexity in the worst case.

    在 Edexcel 的考纲中,编程与抽象、分解和算法效率等理论概念紧密结合。ActiveLearn 通过在实践任务前后嵌入简短的理论测验来强化这种联系。例如,在实现冒泡排序之前,学生可能会被要求解释为什么它在最坏情况下的时间复杂度为 O(n²)。

    Moreover, each programming module includes a ‘Think like a Computer Scientist’ section that poses open‑ended questions. These encourage students to reflect on the limitations of their solutions and consider alternative approaches, fostering deeper understanding rather than rote learning of code.

    此外,每个编程模块都包含一个“像计算机科学家一样思考”部分,提出开放式问题。这些鼓励学生反思自己解决方案的局限性并考虑替代方法,从而培养更深入的理解,而不是死记硬背代码。


    6. Teacher Controls and Class Management | 教师控制与课堂管理

    Teachers using ActiveLearn can assign specific programming tasks to entire classes or individual students, set deadlines, and track progress through a central dashboard. The system highlights students who have not completed tasks or who are repeatedly making the same mistakes, enabling targeted intervention.

    使用 ActiveLearn 的教师可以向整个班级或单个学生分配特定的编程任务、设定截止日期,并通过中央仪表板跟踪进度。系统会突出显示未完成任务或反复犯同样错误的学生,以便进行有针对性的干预。

    The platform also allows teachers to customise the visibility of hints and solutions. For formative assessments, hints can be disabled to simulate exam conditions. Teachers can additionally upload their own coding exercises, aligning the platform further with their lesson plans and the NEA requirements.

    该平台还允许教师自定义提示和解决方案的可见性。对于形成性评估,可以禁用提示以模拟考试条件。教师还可以上传自己的编码练习,使平台更贴合他们的教学计划和 NEA 要求。


    7. Development of Computational Thinking | 计算思维的培养

    Computational thinking – abstraction, decomposition, pattern recognition, and algorithmic design – is at the heart of Edexcel A-Level Computer Science. ActiveLearn programming resources explicitly scaffold these skills. Each task prompts students to break down a problem into smaller parts (decomposition), identify repeated patterns, and generalise solutions (abstraction).

    计算思维——抽象、分解、模式识别和算法设计——是 Edexcel A-Level 计算机科学的核心。ActiveLearn 的编程资源明确地支持这些技能。每项任务都提示学生将问题分解为更小的部分(分解),识别重复的模式,并归纳出解决方案(抽象)。

    For example, a task on creating a text‑based adventure game requires students to design a state machine, handle user input, and implement decision logic. Through this process, they learn to manage complexity and write modular code, directly applying the computational thinking framework assessed in the written exams.

    例如,一个创建基于文本的冒险游戏的任务要求学生设计状态机、处理用户输入并实现决策逻辑。通过这个过程,他们学会管理复杂性并编写模块化代码,直接应用书面考试中评估的计算思维框架。


    8. Preparing for the Non‑Exam Assessment (NEA) | 为非考试评估 (NEA) 做准备

    The NEA component of Edexcel A-Level Computer Science requires students to analyse, design, implement, test, and evaluate a substantial programming project. ActiveLearn provides a dedicated project workspace where students can plan their NEA solutions using design tools, version control, and iterative testing workflows.

    Edexcel A-Level 计算机科学的 NEA 部分要求学生分析、设计、实现、测试和评估一个大型编程项目。ActiveLearn 提供了一个专门的项目工作区,学生可以使用设计工具、版本控制和迭代测试工作流来规划他们的 NEA 解决方案。

    The platform includes exemplar projects with annotated code and examiner commentary, illustrating what distinguishes a top‑band project from a lower‑band one. Students can compare their own progress against these benchmarks, refining their documentation and code efficiency throughout the development cycle.

    该平台包含带有注释代码和考官评语的示范项目,展示了高分项目和低分项目之间的区别。学生可以对照这些基准来比较自己的进度,在整个开发周期中完善他们的文档和代码效率。


    9. Accessing and Navigating the Resource | 访问和浏览资源

    The programming resources can be accessed via the Pearson ActiveLearn student portal using the unique link provided by the school. The interface is intuitive, with a side menu listing all available modules grouped by topic. A search function allows students to find specific concepts quickly, and a progress bar shows overall completion.

    可以通过学校提供的唯一链接,经由 Pearson ActiveLearn 学生门户访问编程资源。界面直观,侧边菜单按主题分组列出了所有可用模块。搜索功能允许学生快速找到特定概念,进度条显示整体完成情况。

    For first‑time users, an interactive tutorial walks through the basic features of the coding environment, such as how to create a new file, run tests, and view feedback. This ensures that technical hurdles do not impede learning from the start.

    对于首次用户,交互式教程将引导他们了解编码环境的基本功能,例如如何创建新文件、运行测试和查看反馈。这确保了技术障碍从一开始就不会阻碍学习。


    10. Technical Support and Community | 技术支持与社区

    Pearson provides extensive technical support for ActiveLearn, including a knowledge base, live chat, and email assistance. Common issues, such as browser compatibility or loading errors, are documented with step‑by‑step troubleshooting guides. Schools can also book training sessions for staff to maximise the use of the platform.

    Pearson 为 ActiveLearn 提供了广泛的技术支持,包括知识库、实时聊天和电子邮件协助。浏览器兼容性或加载错误等常见问题都有逐步故障排除指南。学校还可以为教职员工预订培训课程,以最大化利用该平台。

    Additionally, a moderated student forum allows learners to share tips, ask questions about specific programming challenges, and collaborate on open‑ended projects. This peer‑learning aspect is particularly beneficial for building confidence and exploring creative solutions beyond the curriculum.

    此外,一个受监管的学生论坛允许学习者分享技巧、就特定的编程挑战提问,并在开放式项目上进行协作。这种同伴学习的方面对于建立信心和探索课程之外的创造性解决方案特别有益。

    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Operating Systems: Processes, Scheduling and Memory Management | 操作系统:进程、调度与内存管理

    📚 Operating Systems: Processes, Scheduling and Memory Management | 操作系统:进程、调度与内存管理

    An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. For A-Level Edexcel Computer Science, understanding how an OS handles processes, scheduling, and memory is essential. This article explains these core concepts, blending theory with practical examples.

    操作系统(OS)是管理计算机硬件和软件资源的系统软件,并为计算机程序提供通用服务。对于 A-Level Edexcel 计算机科学,理解操作系统如何处理进程、调度与内存至关重要。本文将剖析这些核心概念,结合理论与实例。

    1. Introduction to Operating Systems | 操作系统简介

    An operating system acts as an interface between the user and the hardware. It hides the complexity of hardware by providing a convenient environment for program execution. Modern OSes are multitasking and multi-user, enabling concurrent execution of multiple processes.

    操作系统充当用户与硬件之间的接口。它通过提供便捷的程序执行环境来隐藏硬件的复杂性。现代操作系统支持多任务和多用户,允许多个进程并发执行。

    2. Functions of an OS | 操作系统的功能

    Key functions of an operating system include: process management, memory management, file system management, I/O management, security and protection, and networking. Each function is critical for the stability and efficiency of a computing system.

    操作系统的关键功能包括:进程管理、内存管理、文件系统管理、输入输出管理、安全与保护以及网络功能。每一个功能对计算系统的稳定性和效率都至关重要。

    3. Process Management | 进程管理

    A process is a program in execution. The OS is responsible for creating, scheduling, and terminating processes. Each process has its own address space and execution context. The OS maintains a process control block (PCB) for each process, storing its state, program counter, registers, and memory limits.

    进程是正在执行的程序。操作系统负责创建、调度和终止进程。每个进程拥有自己的地址空间和执行上下文。操作系统为每个进程维护一个进程控制块(PCB),存储其状态、程序计数器、寄存器和内存限制。

    4. Process States | 进程状态

    A process can be in one of several states: new, ready, running, waiting, or terminated. Transitions occur due to events such as I/O requests or timer interrupts. The state diagram below illustrates these transitions.

    进程可处于以下几种状态之一:新建、就绪、运行、等待或终止。状态转换由 I/O 请求或定时器中断等事件触发。下面的状态图展示了这些转换。

    Process State Description 中文说明
    New Process is being created. 进程正在被创建。
    Ready Process is waiting to be assigned to the CPU. 进程等待分配 CPU。
    Running Instructions are being executed. 指令正在执行。
    Waiting Process is waiting for some event to occur (e.g. I/O completion). 进程等待某个事件发生(如 I/O 完成)。
    Terminated Process has finished execution. 进程执行完毕。

    5. Scheduling Algorithms | 调度算法

    The OS uses scheduling algorithms to decide which process runs next. The goal is to maximise CPU utilisation and provide fair access. Common algorithms include First Come First Served (FCFS), Shortest Job First (SJF), Round Robin (RR), and priority-based scheduling.

    操作系统使用调度算法决定下一个运行的进程。目标是最大化 CPU 利用率并提供公平访问。常见算法包括先来先服务(FCFS)、最短作业优先(SJF)、轮转调度(RR)和基于优先级的调度。

    In Round Robin, each process is given a fixed time quantum (e.g. 20 ms). After the quantum expires, the process is preempted and moved to the back of the ready queue. This is widely used in time-sharing systems.

    在轮转调度中,每个进程获得一个固定的时间片(例如 20 毫秒)。时间片用完后,进程被抢占并移至就绪队列尾部。这广泛用于分时系统。

    6. Memory Management | 内存管理

    Memory management involves allocating and deallocating memory spaces to processes. The OS must protect each process’s memory from others and efficiently use limited physical RAM. Techniques include partitioning, paging, and segmentation.

    内存管理涉及为进程分配和释放内存空间。操作系统必须保护各进程的内存免受其他进程影响,并高效利用有限的物理内存。技术包括分区、分页和分段。

    7. Paging and Segmentation | 分页与分段

    Paging divides physical memory into fixed-size blocks called frames, and logical memory into pages of the same size. A page table maps logical pages to physical frames, enabling non-contiguous allocation. This eliminates external fragmentation.

    分页将物理内存划分为固定大小的块称为帧,将逻辑内存划分为同样大小的页。页表将逻辑页映射到物理帧,实现非连续分配,从而消除了外部碎片。

    Segmentation divides memory into variable-sized segments based on logical units such as functions or data structures. A segment table stores base addresses and limits. Hybrid schemes like paged segmentation combine both approaches.

    分段根据逻辑单元(如函数或数据结构)将内存划分为可变大小的段。段表存储基址和界限。分页式分段等混合方案结合了两种方法。

    8. Virtual Memory | 虚拟内存

    Virtual memory allows the execution of processes that are not entirely in physical memory. The OS moves pages or segments between RAM and secondary storage (disk) using demand paging. This creates an illusion of a larger, contiguous address space.

    虚拟内存允许执行不完全在物理内存中的进程。操作系统通过请求调页在 RAM 和二级存储(磁盘)之间移动页面或分段,创造出更大、连续的地址空间假象。

    When a page is not in memory, a page fault occurs. The OS loads the required page from disk, possibly replacing an existing page using a page replacement algorithm such as Least Recently Used (LRU).

    当所需页面不在内存中时,会发生缺页中断。操作系统从磁盘加载所需页面,并可能使用页面置换算法(如最近最少使用 LRU)替换现有页面。

    9. Interrupts and I/O | 中断与输入输出

    Interrupts are signals to the processor indicating an event that needs immediate attention. Hardware interrupts (e.g. from I/O devices) and software interrupts (traps) cause the CPU to suspend the current task, execute an interrupt service routine (ISR), and resume.

    中断是发送给处理器的信号,表示需要立即关注的事件。硬件中断(例如来自 I/O 设备)和软件中断(陷入)使 CPU 暂停当前任务,执行中断服务程序(ISR),然后恢复。

    The OS manages I/O through device drivers and buffering. Direct Memory Access (DMA) allows devices to transfer data directly to/from memory without CPU involvement for large blocks, reducing overhead.

    操作系统通过设备驱动和缓冲管理 I/O。直接内存访问(DMA)允许设备直接与内存传输数据,无需 CPU 参与大量数据的搬运,从而降低开销。

    10. Concurrency and Deadlock | 并发与死锁

    Concurrency arises when multiple processes execute simultaneously. The OS must synchronise access to shared resources to prevent race conditions. Mechanisms like semaphores, mutex locks, and monitors enforce mutual exclusion.

    并发在多个进程同时执行时出现。操作系统必须同步对共享资源的访问以防止竞态条件。信号量、互斥锁和管程等机制强制实现互斥。

    A deadlock is a situation where two or more processes are each waiting for resources held by the other, resulting in a standstill. Four necessary conditions for deadlock (Coffman’s conditions) are mutual exclusion, hold and wait, no preemption, and circular wait. Prevention or avoidance strategies (e.g. Banker’s algorithm) are used.

    死锁是指两个或多个进程各自等待对方持有的资源,导致系统停滞。死锁的四个必要条件(科夫曼条件)是互斥、持有并等待、不可抢占和循环等待。采用预防或避免策略(如银行家算法)应对。

    11. OS Security | 操作系统安全

    OS security involves authentication, authorisation, and encryption to protect data and resources. User accounts, file permissions, and access control lists (ACLs) restrict unauthorised access. Modern OSes also include firewalls and sandboxing for applications.

    操作系统安全涉及身份验证、授权和加密,以保护数据和资源。用户账户、文件权限和访问控制列表(ACL)限制未授权访问。现代操作系统还包含防火墙和应用程序沙箱。

    12. Real-world OS Examples | 现实操作系统示例

    Popular operating systems like Windows, Linux, and macOS implement these concepts in different ways. Linux uses a monolithic kernel with loadable modules, supports preemptive multitasking, and employs the Completely Fair Scheduler (CFS). Windows uses a hybrid kernel and several scheduling priority classes.

    流行的操作系统,如 Windows、Linux 和 macOS,以不同方式实现了这些概念。Linux 使用具有可加载模块的单体内核,支持抢占式多任务,并采用完全公平调度器(CFS)。Windows 使用混合内核和多种调度优先级类。

    Understanding the theoretical framework of operating systems equips students to analyse and evaluate performance, reliability, and security in a variety of computing environments.

    理解操作系统的理论框架,使学生能够分析和评估各种计算环境中的性能、可靠性和安全性。

    Published by TutorHao | Computer Science Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming Concepts | 面向对象编程概念

    📚 Object-Oriented Programming Concepts | 面向对象编程概念

    Object-oriented programming (OOP) is a paradigm that organises software design around data, or objects, rather than functions and logic. In A-Level Edexcel Computer Science, mastering OOP principles is essential for writing robust, reusable, and maintainable code. This article explores the core concepts of OOP, including classes, objects, encapsulation, inheritance, polymorphism, and abstraction, and explains how they are applied in modern programming languages such as Python, Java, or C#.

    面向对象编程(OOP)是一种以数据(即对象)而非函数和逻辑为中心来组织软件设计的范式。在A-Level Edexcel计算机科学课程中,掌握OOP原则对于编写健壮、可复用且易于维护的代码至关重要。本文探讨了OOP的核心概念,包括类、对象、封装、继承、多态和抽象,并说明了它们在Python、Java或C#等现代编程语言中的应用方式。

    1. Introduction to OOP | 面向对象编程简介

    OOP models real-world entities as objects that hold both state (attributes) and behaviour (methods). Unlike procedural programming, which separates data from procedures, OOP bundles them together, promoting modularity and code organisation.

    OOP将现实世界中的实体建模为对象,这些对象同时保存状态(属性)和行为(方法)。与将数据与过程分离的面向过程编程不同,OOP将它们捆绑在一起,从而促进了模块化和代码组织。


    2. Classes and Objects | 类与对象

    A class is a blueprint or template that defines the attributes and methods common to a group of objects. An object is an instance of a class, created at runtime with specific values for its attributes. For example, a class Car may have attributes like colour and speed, and methods such as accelerate(). An object myCar of type Car can be instantiated with colour ‘red’ and initial speed 0.

    类是定义一组对象共有属性和方法的蓝图或模板。对象是类的实例,在运行时创建,并具有特定的属性值。例如,一个Car类可以具有colourspeed等属性,以及accelerate()等方法。可以创建一个类型为Car的对象myCar,初始颜色为’red’,速度为0。


    3. Encapsulation and Data Hiding | 封装与数据隐藏

    Encapsulation restricts direct access to an object’s internal data by making attributes private. Access is provided only through public methods (getters and setters), which allows validation and control over how data is modified. This reduces unintended interference and enhances security. For instance, a BankAccount class might have a private balance attribute that can only be changed via a deposit(amount) method which checks for positive values.

    封装通过将属性设为私有来限制对对象内部数据的直接访问。只能通过公共方法(getter 和 setter)进行访问,这样可以实现对数据修改方式的验证和控制。这减少了意外干扰并增强了安全性。例如,一个BankAccount类可能有一个私有的balance属性,只能通过检查正值的deposit(amount)方法来更改。


    4. Inheritance | 继承

    Inheritance enables a new class (child or subclass) to derive properties and methods from an existing class (parent or superclass). This promotes code reuse and establishes a hierarchical relationship. In Edexcel specifications, the keyword extends (Java) or parentheses syntax (Python) is used. A subclass can override inherited methods to provide specialised behaviour.

    继承使新类(子类)能够从现有类(父类或超类)派生属性和方法。这促进了代码重用并建立了层次关系。在Edexcel考纲中,使用关键字extends(Java)或括号语法(Python)。子类可以重写继承的方法来提供专门的行为。

    • Single inheritance: a subclass inherits from one superclass.
    • 单一继承:子类从一个超类继承。
    • Multiple inheritance: a subclass inherits from multiple superclasses (supported in Python, not directly in Java).
    • 多重继承:子类从多个超类继承(Python支持,Java不直接支持)。

    5. Polymorphism | 多态

    Polymorphism means ‘many forms’ and allows objects of different classes to be treated as objects of a common superclass. The most common form is overriding, where a subclass provides its own implementation of a method defined in the parent. This enables code to work with objects generically, calling the same method name but getting class-specific behaviour.

    多态意味着“多种形态”,允许将不同类的对象视为公共超类的对象。最常见的形式是重写,即子类提供自己对父类中定义的方法的实现。这使得代码能够以通用方式操作对象,调用相同的方法名但获得特定于类的行为。


    6. Abstraction | 抽象

    Abstraction focuses on exposing only essential features of an object while hiding complex implementation details. Abstract classes and interfaces are tools for abstraction. An abstract class cannot be instantiated; it is meant to be subclassed, and may contain abstract methods (without body) that subclasses must implement. This simplifies the developer’s view and supports design by contract.

    抽象专注于仅暴露对象的基本特性,同时隐藏复杂的实现细节。抽象类和接口是实现抽象的工具。抽象类不能被实例化;它旨在被子类化,并且可以包含抽象方法(没有方法体),子类必须实现这些方法。这简化了开发者的视角,并支持契约式设计。


    7. Constructors and Destructors | 构造方法与析构方法

    Constructors are special methods called when an object is instantiated. They initialise the object’s state. In Python, the __init__ method acts as the constructor, while in Java the constructor has the same name as the class. Destructors (or finalisers) clean up resources before an object is removed; Python uses __del__, Java uses a garbage collector that invokes finalize() (deprecated). Memory management is often automatic.

    构造方法是在对象实例化时调用的特殊方法,用于初始化对象的状态。在Python中,__init__方法充当构造方法,而在Java中,构造方法与类同名。析构方法(或终结器)在对象被移除之前清理资源;Python使用__del__,Java使用调用finalize()(已弃用)的垃圾收集器。内存管理通常是自动的。


    8. Association, Aggregation and Composition | 关联、聚合与组合

    These relationships describe how objects interact. Association is a generic ‘uses-a’ connection. Aggregation is a ‘has-a’ relationship where the child can exist independently of the parent (e.g., a department has professors). Composition is a stronger ‘has-a’ where the child’s lifecycle depends on the parent (e.g., a house has rooms; rooms cannot exist without the house). Understanding these helps in designing class diagrams.

    这些关系描述了对象之间的交互方式。关联是一种通用的“使用”连接。聚合是一种“拥有”关系,其中子对象可以独立于父对象存在(例如,院系拥有教授)。组合是一种更强的“拥有”关系,其中子对象的生命周期依赖于父对象(例如,房子拥有房间;房间不能脱离房子存在)。理解这些有助于设计类图。


    9. UML Class Diagrams | UML类图

    In Edexcel examinations, candidates must interpret and draw Unified Modelling Language (UML) class diagrams. A class is represented as a rectangle divided into three sections: class name, attributes (with visibility markers like + public, – private), and methods. Inheritance is shown with a hollow triangle arrow from subclass to superclass. Association, aggregation, and composition use lines with different notations.

    在Edexcel考试中,考生必须能够解读和绘制统一建模语言(UML)类图。类用分为三部分的矩形表示:类名、属性(带有可见性标记,如+表示公共,-表示私有)和方法。继承关系用从子类指向超类的空心三角箭头表示。关联、聚合和组合则使用带有不同符号的线条。


    10. Advantages and Disadvantages of OOP | 面向对象编程的优缺点

    OOP promotes code reusability through inheritance, modularity through classes, and data security through encapsulation. However, it can introduce complexity, and objects may consume more memory than simple data structures. Designing a good OOP system requires careful planning and can be overkill for small scripts.

    OOP通过继承促进了代码重用,通过类增强了模块化,通过封装提高了数据安全性。然而,它可能带来复杂性,对象可能比简单的数据结构消耗更多内存。设计一个好的OOP系统需要精心规划,对于小型脚本可能过于复杂。


    11. Practical Example in Python | Python实例

    Below is a concise Python example illustrating class, inheritance, and polymorphism. The Animal superclass defines a method speak(), and the Dog subclass overrides it. Encapsulation is shown with a private attribute.

    下面是一个简明的Python示例,展示了类、继承和多态。超类Animal定义了一个方法speak(),子类Dog重写了它。封装通过私有属性来展示。


    class Animal:
      def __init__(self, name):
        self.__name = name # private
      def speak(self):
        return 'Sound'

    class Dog(Animal):
      def speak(self):
        return 'Woof'

    a = Animal('generic')
    d = Dog('Buddy')
    print(a.speak()) # Sound
    print(d.speak()) # Woof

    代码中__name属性为私有,Dog类通过方法重写展现了多态。这体现了OOP的核心思想。


    12. Exam Tips for Edexcel A-Level Programming | Edexcel A-Level编程备考建议

    When answering OOP questions, clearly define each term and provide a code snippet or UML fragment. Use precise terminology: ‘encapsulation’, not just ‘hiding data’; distinguish between aggregation and composition. Traceability to the specification is key – practise past papers focusing on class design and comparing procedural vs OOP approaches.

    在回答OOP问题时,要清晰定义每个术语,并提供代码片段或UML片段。使用精确的术语:叫“封装”而不仅仅是“隐藏数据”;区分聚合和组合。紧扣考纲是关键——练习真题,重点关注类设计以及面向过程与OOP方法的比较。

    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Searching Algorithms: Linear Search and Binary Search | 搜索算法:线性搜索与二分搜索

    📚 Searching Algorithms: Linear Search and Binary Search | 搜索算法:线性搜索与二分搜索

    Searching is a fundamental operation in computer science, allowing programs to locate a specific element within a data collection. This article focuses on two core search algorithms specified by Edexcel A-Level Computer Science: linear search and binary search. Understanding their mechanisms, efficiency, and practical trade-offs is essential for both exams and real-world programming.

    搜索是计算机科学中的一项基本操作,它使程序能够在数据集合中定位特定元素。本文重点介绍 Edexcel A-Level 计算机科学课程指定的两种核心搜索算法:线性搜索和二分搜索。理解它们的工作机制、效率以及实际权衡对考试和现实世界的编程都至关重要。


    1. Introduction to Searching Algorithms | 搜索算法简介

    A search algorithm retrieves an item from a data structure based on a given key. The choice of algorithm affects how quickly a result can be found. In the Edexcel specification, students must be able to describe, compare, and implement linear and binary search, as well as evaluate their suitability for different scenarios.

    搜索算法根据给定的键从数据结构中检索项目。算法的选择会影响找到结果的速度。在 Edexcel 大纲中,学生必须能够描述、比较和实现线性搜索与二分搜索,并评估它们在不同情境下的适用性。


    2. Linear Search – The Simple Approach | 线性搜索——简单方法

    Linear search, also called sequential search, inspects each element of a list one by one until the target is found or the end is reached. It does not require the data to be sorted, making it universally applicable. The algorithm uses a single loop to traverse the array, checking each element against the search key.

    线性搜索,也叫顺序搜索,逐个检查列表中的每个元素,直到找到目标或到达末尾。它不要求数据有序,因此普遍适用。算法使用一个循环遍历数组,将每个元素与搜索键进行比对。


    3. How Linear Search Works | 线性搜索如何工作

    The procedure begins at index 0 and compares the element with the target value. If they match, the index is returned. If not, the algorithm moves to the next index. This repeats until a match is found. If the loop finishes without a match, a value such as -1 is returned to indicate failure. The algorithm is straightforward and easy to code.

    过程从索引 0 开始,将元素与目标值比较。如果匹配,则返回该索引。如果不匹配,算法移至下一个索引。如此重复,直到找到匹配项。如果循环结束仍未找到,则返回 -1 之类的值表示未找到。该算法直接且易于编码。


    4. Efficiency of Linear Search | 线性搜索的效率

    In the worst case, the target is at the very end of the list or not present, requiring n comparisons for a list of size n. This gives linear search a time complexity of O(n). In the best case, the element is found at the first position, O(1). The average case also falls under O(n). Because it does not exploit any ordering, linear search can be slow on large datasets.

    最坏情况下,目标位于列表末尾或不存在,对于大小为 n 的列表需要 n 次比较。这使线性搜索的时间复杂度为 O(n)。最好情况下,元素在第一个位置找到,O(1)。平均情况也属于 O(n)。由于不利用任何顺序,线性搜索在大数据集上可能很慢。


    5. Binary Search – Divide and Conquer | 二分搜索——分治法

    Binary search dramatically reduces the number of comparisons by repeatedly dividing the search interval in half. It is a divide-and-conquer algorithm that requires the list to be sorted beforehand. The algorithm compares the target with the middle element; depending on the result, it discards the half that cannot contain the target, continuing on the remaining half.

    二分搜索通过反复将搜索区间减半,显著减少了比较次数。它是一种分治算法,需要列表事先排序。算法将目标与中间元素比较;根据结果,丢弃不可能包含目标的那一半,在剩下的一半上继续搜索。


    6. Preconditions for Binary Search | 二分搜索的前提条件

    The array or list must be sorted in ascending or descending order. If the data is unsorted, binary search will not work correctly and may miss the target or loop indefinitely. Sorting itself can be costly, so binary search is most effective when multiple searches are performed on the same sorted data structure.

    数组或列表必须按升序或降序排列。如果数据未排序,二分搜索将无法正确工作,可能找不到目标或无限循环。排序本身可能代价高昂,因此二分搜索最适用于对同一已排序数据结构执行多次搜索的情况。


    7. Step-by-Step Binary Search | 二分搜索逐步解析

    Two pointers, low and high, mark the current search boundaries. Initially, low = 0 and high = len(list)-1. While low <= high, compute mid = (low + high) // 2. If the middle element equals the target, return mid. If the target is smaller, set high = mid - 1; if larger, set low = mid + 1. If low surpasses high, the item is not found and the procedure returns an error value.

    用两个指针 low 和 high 标记当前搜索边界。初始时 low = 0, high = len(list)-1。当 low <= high,计算 mid = (low + high) // 2。如果中间元素等于目标,返回 mid。如果目标更小,则设 high = mid - 1;如果更大,则设 low = mid + 1。一旦 low 超过 high,表示未找到,程序返回错误值。


    8. Efficiency of Binary Search | 二分搜索的效率

    Each comparison halves the search space, so the maximum number of steps is about log₂(n). Thus, binary search has a time complexity of O(log n) in the worst and average cases. The best case remains O(1) if the middle element happens to be the target. This logarithmic efficiency makes binary search vastly superior to linear search on large sorted datasets.

    每次比较将搜索空间减半,因此最大步数大约为 log₂(n)。这样,二分搜索在最坏和平均情况下的时间复杂度为 O(log n)。最好情况如果中间元素恰好是目标,仍为 O(1)。这种对数级效率使得二分搜索在大型有序数据集上远优于线性搜索。


    9. Comparing Linear and Binary Search | 线性搜索与二分搜索的比较

    Linear search works on any list, is simple to implement, and performs well on small or nearly full arrays where the target appears early. Binary search requires sorted data and more complex logic, but it excels with large n. A comparison of their worst-case complexities shows that for n = 1,000,000, linear search may take 1 million checks, while binary search needs at most 20. The trade-off lies in the sorting overhead.

    线性搜索适用于任何列表,实现简单,在小型数组或目标出现较早时表现良好。二分搜索需要排序数据和更复杂的逻辑,但在 n 很大时表现优异。最坏情况复杂度的对比表明,当 n = 1,000,000 时,线性搜索可能需要 100 万次检查,而二分搜索最多只需 20 次。权衡在于排序的开销。


    10. Implementing in Pseudocode and Python | 伪代码与Python实现

    Edexcel expects students to write and trace both algorithms. Below are concise examples. For linear search in Python:

    def linear_search(arr, target):
        for i in range(len(arr)):
            if arr[i] == target:
                return i
        return -1
    

    For binary search:

    def binary_search(arr, target):
        low, high = 0, len(arr)-1
        while low <= high:
            mid = (low + high) // 2
            if arr[mid] == target:
                return mid
            elif arr[mid] < target:
                low = mid + 1
            else:
                high = mid - 1
        return -1
    

    Edexcel 期望学生能够编写和追踪这两种算法。下面是简洁的示例。Python 线性搜索:

    def linear_search(arr, target):
        for i in range(len(arr)):
            if arr[i] == target:
                return i
        return -1
    

    二分搜索:

    def binary_search(arr, target):
        low, high = 0, len(arr)-1
        while low <= high:
            mid = (low + high) // 2
            if arr[mid] == target:
                return mid
            elif arr[mid] < target:
                low = mid + 1
            else:
                high = mid - 1
        return -1
    

    11. Searching in Real-world Applications | 实际应用中的搜索

    Linear search is often used in small unsorted lists, such as finding a name in a short contact list, or when scanning streaming data where sorting isn't possible. Binary search underpins operations in database indexing, dictionary lookups, and filesystem searches on sorted keys. Understanding both helps programmers design appropriate data structures.

    线性搜索常用在小的无序列表中,比如在简短的联系人列表中查找姓名,或者在无法排序的流式数据中扫描。二分搜索则支撑着数据库索引、字典查找以及基于排序键的文件系统搜索等操作。理解两者有助于程序员设计合适的数据结构。


    12. Exam Tips and Common Pitfalls | 考试技巧与常见误区

    When describing binary search, always emphasise that the list must be sorted. Many candidates lose marks for forgetting this crucial detail. Trace tables are common in exams; practise tracking low, mid, and high values step by step. Remember that binary search uses integer division for the midpoint. For linear search, be clear that the algorithm stops when found, which is essential for efficiency calculations.

    在描述二分搜索时,务必强调列表必须有序。许多考生因遗漏这一关键细节而失分。考试中常出现跟踪表;请逐步练习记录 low、mid 和 high 的值。记住二分搜索的中点使用整数除法。对于线性搜索,要明确算法找到目标后即停止,这对效率计算至关重要。


    Published by TutorHao | Computer Science Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Mastering Programming Operations: Arithmetic, Relational, and Boolean | 掌握编程运算符:算术、关系与布尔运算

    📚 Mastering Programming Operations: Arithmetic, Relational, and Boolean | 掌握编程运算符:算术、关系与布尔运算

    Operations are the fundamental building blocks of any programming language. In Edexcel A-Level Computer Science, operators allow you to perform calculations, compare data, and combine logical conditions. Whether you are writing pseudocode or analysing algorithms, a solid grasp of arithmetic, relational, and Boolean operations is essential. This article explores each category of operations, their syntax, precedence rules, and common pitfalls, providing you with the knowledge you need to tackle exam questions confidently.

    运算是任何编程语言的基本构件。在 Edexcel A-Level 计算机科学中,运算符让你能够执行计算、比较数据并组合逻辑条件。无论你是在编写伪代码还是分析算法,牢固掌握算术、关系和布尔运算都至关重要。本文将深入探讨每一类运算符的语法、优先级规则和常见陷阱,为你自信地应对考试题目提供所需的知识。


    1. Understanding Operations in Programming | 理解编程中的运算符

    In programming, an operation is an action performed on one or more operands (values) to produce a result. Operators are the symbols or keywords that represent these actions, such as +, -, <, AND, and MOD. The Edexcel specification expects you to be able to use operators correctly within pseudocode and to evaluate expressions involving multiple operations. Operations are classified broadly into arithmetic, relational, and Boolean categories, each serving a distinct purpose in algorithm design. Mastering their behaviour, particularly with different data types and precedence levels, will help you avoid logic errors and write more efficient solutions.

    在编程中,运算是施加于一个或多个操作数(值)并产生结果的操作。运算符是表示这些操作的符号或关键字,例如 +、-、<、AND 和 MOD。Edexcel 大纲要求你能够在伪代码中正确使用运算符,并能够计算包含多种运算的表达式。运算符大致分为算术、关系和布尔三类,每一类在算法设计中都有独特的用途。熟练掌握它们的行为,尤其是与不同数据类型和优先级相关的情况,将帮助你避免逻辑错误并写出更高效的解决方案。


    2. Arithmetic Operations: The Basics | 算术运算符基础

    Arithmetic operators perform standard mathematical calculations on numeric operands. The core operators in pseudocode are + (addition), – (subtraction), * (multiplication), and / (real division). In addition, Edexcel pseudocode provides DIV for integer division and MOD for the remainder. For example, 10 / 4 yields 2.5 in real division, but 10 DIV 4 gives 2, and 10 MOD 4 gives 2 as well. Integer division truncates the result toward zero when both operands are positive, but care must be taken with negative numbers. When constructing expressions, parentheses ( ) can be used to group operations and override the default order of evaluation, ensuring clarity and correctness.

    算术运算符对数值操作数执行标准的数学计算。伪代码中的核心运算符包括 +(加)、-(减)、*(乘)和 /(实数除法)。此外,Edexcel 伪代码提供了 DIV 用于整数除法,MOD 用于取余数。例如,10 / 4 的实数除法结果是 2.5,而 10 DIV 4 的结果是 2,10 MOD 4 的结果是 2。当两个操作数都为正时,整数除法将结果向零截断,但对于负数需要特别小心。在构造表达式时,可以使用括号 ( ) 对运算分组并覆盖默认的计算顺序,以确保表达式的清晰和准确。


    3. Division and Modulus in Detail | 详解除法与取模运算

    Understanding the difference between real division (/) and integer division (DIV) is a key skill. Real division retains the fractional part and typically yields a float, while DIV discards the remainder and always returns an integer. The modulus operator MOD returns the remainder of an integer division. Common use cases include checking divisibility and cycling through indices. For instance, to determine whether a number num is even, you would write IF num MOD 2 = 0 THEN. To cycle through an array of size n, you might use index <- (index + 1) MOD n. Practising with trace tables can help you visualise each step and avoid off-by-one errors, which are frequently tested in the exam.

    理解实数除法 (/) 和整数除法 (DIV) 的区别是一项关键技能。实数除法保留小数部分,通常产生浮点数,而 DIV 会丢弃余数并始终返回整数。取模运算符 MOD 返回整数除法的余数。常见的用例包括检查整除性和循环遍历索引。例如,要判断一个整数 num 是否为偶数,可以写为 IF num MOD 2 = 0 THEN。要循环遍历大小为 n 的数组,可以使用 index <- (index + 1) MOD n。结合跟踪表进行练习有助于你可视化每一步计算,并避免偏差一位的错误,这些错误在考试中经常出现。


    4. Relational (Comparison) Operations | 关系(比较)运算符

    Relational operators compare two values and produce a Boolean outcome (TRUE or FALSE). The standard operators in Edexcel pseudocode are = (equal to), ≠ (not equal to, also written as <>), < (less than), ≤ (less than or equal), > (greater than), and ≥ (greater than or equal). These operators are essential for building conditions in selection and iteration constructs. For example, IF score ≥ 70 AND attendance > 80 THEN. When comparing strings, the comparison is typically based on the character codes, so ‘A’ < ‘B’ returns TRUE. The exam will specify the character set if needed, so you only need to apply the given rules.

    关系运算符用于比较两个值并产生布尔结果(TRUE 或 FALSE)。Edexcel 伪代码中的标准运算符有 =(等于)、≠(不等于,也可写作 <>)、<(小于)、≤(小于等于)、>(大于)和 ≥(大于等于)。这些运算符对于在选择和迭代结构中构建条件至关重要。例如,IF score ≥ 70 AND attendance > 80 THEN。在比较字符串时,通常基于字符代码进行比较,因此 ‘A’ < ‘B’ 返回 TRUE。考试中如果需要会指定字符集,因此你只需应用给定的规则。


    5. Boolean Logic and Logical Operators | 布尔逻辑与逻辑运算符

    Boolean operators work on Boolean values and return a Boolean result. The three fundamental operators are AND, OR, and NOT. The truth tables below define their behaviour:

    布尔运算符对布尔值进行操作并返回布尔结果。三个基本运算符是 AND、OR 和 NOT。下面的真值表定义了它们的行为:

    A B A AND B
    TRUE TRUE TRUE
    TRUE FALSE FALSE
    FALSE TRUE FALSE
    FALSE FALSE FALSE

    Similarly, A OR B is TRUE if at least one of A or B is TRUE. NOT simply negates the operand: NOT TRUE is FALSE, and NOT FALSE is TRUE. Logical operators are extremely useful for combining multiple conditions. For instance, checking whether a number lies within a range: IF x > 10 AND x &lt

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming (OOP) | 面向对象编程

    📚 Object-Oriented Programming (OOP) | 面向对象编程

    Object-Oriented Programming (OOP) is a programming paradigm that organises code around objects, which encapsulate data and behaviour. For Edexcel A-Level Computer Science, understanding OOP is essential as it underpins modern software development. This article covers key OOP concepts including classes, objects, inheritance, polymorphism, and encapsulation, with examples in Python to illustrate each concept clearly.

    面向对象编程(OOP)是一种将代码组织为对象的编程范式,对象封装了数据和行为。对于Edexcel A-Level计算机科学而言,理解OOP至关重要,因为它是现代软件开发的基础。本文涵盖类、对象、继承、多态和封装等关键OOP概念,并使用Python示例进行清晰说明。

    1. Introduction to OOP | 面向对象编程简介

    OOP models real-world entities as objects that have attributes (data) and methods (behaviours). Unlike procedural programming, where functions operate on separate data, OOP bundles them together, making complex systems easier to manage and extend.

    OOP将现实世界实体建模为对象,对象具有属性(数据)和方法(行为)。与过程式编程中函数操作分离的数据不同,OOP将数据和行为捆绑在一起,使复杂系统更易于管理和扩展。

    A class serves as a blueprint for creating objects. For example, a class Car may define attributes like color and methods like drive(). Each individual car is an object instance of this class. This blueprint analogy helps developers think in terms of real-world concepts.

    类作为创建对象的蓝图。例如,一个Car类可以定义如color的属性和drive()的方法。每一辆具体的车都是该类的一个对象实例。这种蓝图类比有助于开发者使用现实世界概念进行思考。

    The four fundamental pillars of OOP – encapsulation, inheritance, polymorphism, and abstraction – improve code reusability, modularity, and maintainability. Edexcel syllabuses often require you to identify and apply these pillars in given scenarios.

    OOP的四大支柱——封装、继承、多态和抽象——提高了代码的可重用性、模块化和可维护性。Edexcel大纲通常要求你在给定场景中识别和应用这些支柱。


    2. Classes and Objects | 类与对象

    In Python, you define a class using the class keyword followed by the class name. By convention, class names use CamelCase (e.g., BankAccount). An object is created by calling the class as if it were a function. This process is called instantiation.

    在Python中,使用class关键字后跟类名来定义类。按照惯例,类名使用驼峰式大小写(例如BankAccount)。通过像调用函数一样调用类来创建对象,这个过程称为实例化。

    The self parameter refers to the specific instance of the class and is always the first parameter in method definitions. It allows you to access instance attributes and methods within the class. Although you can name it anything, using self is a strong convention.

    self参数指向类的具体实例,并且在方法定义中始终是第一个参数。通过它你可以在类内部访问实例属性和方法。虽然你可以给它起任何名字,但使用self是一个强约定。

    Example: class Dog:
      def bark(self):
        print('Woof!')
    my_dog = Dog()
    my_dog.bark(). Here my_dog is an object of the Dog class, and calling bark() executes the method on that object.

    示例:class Dog:
      def bark(self):
        print('汪!')
    my_dog = Dog()
    my_dog.bark()。这里my_dogDog类的一个对象,调用bark()会在该对象上执行方法。

    You can check the type of an object with type() or verify it is an instance of a class using isinstance(). These functions are useful for debugging and type checking.

    你可以使用type()检查对象的类型,或使用isinstance()验证它是否是某个类的实例。这些函数在调试和类型检查中非常有用。


    3. Attributes and Methods | 属性与方法

    Instance attributes are usually initialised inside the __init__ method using self.attribute_name. They belong to the object and can have different values for each instance. Attributes store the state of an object.

    实例属性通常在__init__方法内使用self.attribute_name进行初始化。它们属于对象,并且每个实例可以有不同的值。属性存储对象的状态。

    Methods are functions defined inside a class that operate on the object’s data. They typically take self as the first parameter. For example, a method deposit(amount) in a BankAccount class increases the balance attribute.

    方法是定义在类内部的函数,对对象的数据进行操作。它们通常以self作为第一个参数。例如,BankAccount类中的方法deposit(amount)会增加余额属性。

    In Python, access modifiers such as public and private are handled by convention. A single underscore _ before a name (e.g., _balance) suggests protected access, while a double underscore __ triggers name mangling to simulate private. There is no strict enforcement, but it guides responsible usage.

    Python中通过约定处理访问修饰符。名称前的单下划线_(例如_balance)暗示受保护访问,而双下划线__会触发名称改写以模拟私有。虽然没有严格强制,但它引导了负责任的使用。

    You can also define class methods and static methods using @classmethod and @staticmethod decorators. Class methods receive the class (cls) as the first argument, while static methods do not receive an implicit first argument and behave like plain functions scoped to the class.

    你还可以使用@classmethod@staticmethod装饰器定义类方法和静态方法。类方法接收类(cls)作为第一个参数,而静态方法不接收隐式的第一个参数,其行为类似于限域在类内的普通函数。


    4. The Constructor Method (__init__) | 构造方法 (__init__)

    The __init__ method is a special method automatically called when an object is instantiated. It initialises the object’s state by setting initial values for its attributes. Every class where objects need starting data should define it.

    __init__方法是一种特殊方法,在对象实例化时自动调用。它通过设置属性的初始值来初始化对象的状态。任何需要初始数据的类都应该定义它。

    Syntax: class Student:
      def __init__(self, name, age):
        self.name = name
        self.age = age. You can assign default parameter values to make some attributes optional, for instance def __init__(self, name, age=18):.

    语法:class Student:
      def __init__(self, name, age):
        self.name = name
        self.age = age。你可以为参数设置默认值使某些属性成为可选,例如def __init__(self, name, age=18):

    When a subclass overrides __init__, it should often call super().__init__(...) to ensure the parent class is properly initialised. This is crucial for building upon inherited functionality without losing the base setup.

    当子类重写__init__时,通常应调用super().__init__(...)以确保父类被正确初始化。这对于在继承功能之上构建而不丢失基础设置至关重要。

    If no __init__ is defined, Python provides a default no-argument constructor that does nothing. However, relying on it prevents attribute initialisation at creation time, which is rarely desirable in well-designed classes.

    如果没有定义__init__,Python提供一个默认的无参数构造方法,它什么也不做。然而,依赖它将导致创建时无法初始化属性,这在设计良好的类中很少是可取的。


    5. Encapsulation and Access Control | 封装与访问控制

    Encapsulation bundles data and methods within a class, restricting direct manipulation of an object’s internal state. This helps prevent accidental corruption and enforces controlled interaction through a well-defined interface.

    封装将数据和方法捆绑在类中,限制对对象内部状态的直接操作。这有助于防止意外破坏,并通过明确定义的接口强制受控交互。

    In Python, encapsulation is achieved with naming conventions. Attributes prefixed with a single underscore are considered protected, indicating they should not be accessed outside the class or its subclasses unless necessary. Double underscores cause name mangling to discourage accidental access.

    在Python中,封装通过命名约定实现。带有单下划线前缀的属性被视为受保护,表示它们不应在类或其子类之外随意访问。双下划线会引发名称改编以阻止意外访问。

    Getter and setter methods provide controlled access to attributes. The @property decorator makes a method callable like an attribute (getter), while @attribute.setter validates and sets the value. This allows you to add logic without changing the external interface.

    Getter和setter方法提供对属性的受控访问。@property装饰器使方法可以像属性一样被调用(getter),而@attribute.setter则验证并设置值。这使你可以在不改变外部接口的情况下添加逻辑。

    Example: @property
    def age(self):
      return self._age
    @age.setter
    def age(self, value):
      if value < 0: raise ValueError
      self._age = value. Encapsulation ensures the internal _age is protected from direct invalid assignments.

    示例:@property
    def age(self):
      return self._age
    @age.setter

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming | 面向对象编程

    📚 Object-Oriented Programming | 面向对象编程

    Object-Oriented Programming (OOP) is a paradigm that organises software design around data, or objects, rather than functions and logic. It enables programmers to model real-world entities, making code easier to maintain, reuse and extend. In A-Level Edexcel Computer Science, understanding OOP is essential, as it underpins many modern programming languages and software engineering principles. This article explains the core concepts of OOP with clear examples and highlights their relevance to the Edexcel specification.

    面向对象编程(OOP)是一种以数据(即对象)而非功能与逻辑为核心的软件设计范式。它让程序员能够对现实世界中的实体进行建模,从而使代码更易于维护、复用和扩展。在 Edexcel A-Level 计算机科学课程中,理解面向对象编程至关重要,因为它是许多现代编程语言和软件工程原则的基础。本文将通过清晰的示例解释 OOP 的核心概念,并突出其在 Edexcel 大纲中的相关性。

    1. Introduction to OOP | 面向对象编程导论

    OOP is a programming paradigm centred on the concept of objects, which are instances of classes. A class acts as a blueprint, defining the properties (attributes) and behaviours (methods) that its objects will have. Unlike procedural programming, which separates data from procedures, OOP bundles them together, leading to better organisation and modularity. This approach mirrors how humans perceive the world: as collections of interacting entities.

    面向对象编程是一种以对象(类的实例)为核心的编程范式。类相当于蓝图,定义了其对象将具有的属性(数据)和行为(方法)。与将数据与过程分离的过程式编程不同,OOP 将它们捆绑在一起,从而提高了组织性和模块化程度。这种方法反映了人类感知世界的方式:世界是由相互作用的实体组成的。


    2. Classes and Objects | 类与对象

    A class is a template for creating objects. For example, a class Car might have attributes like colour and speed, and methods like accelerate() and brake(). An object is a specific instance of the class, such as myCar = Car("red", 0). Each object has its own copy of the attributes, so myCar.colour could be “red” while anotherCar.colour is “blue”.

    类是创建对象的模板。例如,Car 类可能具有 colorspeed 等属性,以及 accelerate()brake() 等方法。对象是该类的具体实例,例如 myCar = Car("red", 0)。每个对象都有自己的属性副本,因此 myCar.color 可能是 “red”,而 anotherCar.color 是 “blue”。

    class Car:
        def __init__(self, colour, speed):
            self.colour = colour
            self.speed = speed
    
        def accelerate(self, increment):
            self.speed += increment
    

    3. Attributes and Methods | 属性与方法

    Attributes store the state of an object. They can be public, private or protected depending on the language’s access modifiers. Methods define the object’s behaviour and often operate on the attributes. For instance, a BankAccount class might have a private attribute balance and public methods deposit() and withdraw() to ensure controlled access to the balance.

    属性存储对象的状态。根据语言的访问修饰符,它们可以是公有的、私有的或受保护的。方法定义了对象的行为,通常操作这些属性。例如,BankAccount 类可能有一个私有属性 balance,以及公有方法 deposit()withdraw(),以确保对余额的访问受到控制。


    4. Encapsulation | 封装

    Encapsulation is the bundling of data with the methods that operate on that data, and restricting direct access to some of an object’s components. This is typically achieved by making attributes private and providing public getter and setter methods. Encapsulation protects the integrity of the data and hides the internal implementation details from the outside world. In Edexcel A-Level, you’ll encounter encapsulation as a key principle that reduces complexity and prevents accidental interference.

    封装是将数据与操作该数据的方法捆绑在一起,并限制对对象某些组件的直接访问。这通常通过将属性设为私有并提供公有的 getter 和 setter 方法来实现。封装保护了数据的完整性,并向外部隐藏了内部实现细节。在 Edexcel A-Level 课程中,你将学到封装是降低复杂性并防止意外干扰的关键原则。

    class Student:
        def __init__(self, name):
            self.__name = name   # private attribute
    
        def get_name(self):
            return self.__name
    
        def set_name(self, new_name):
            if new_name:
                self.__name = new_name
    

    5. Inheritance | 继承

    Inheritance allows a class (subclass) to inherit attributes and methods from another class (superclass). This promotes code reuse and establishes a natural hierarchy. For example, a Dog class can inherit from an Animal class, gaining basic methods like eat() while adding its own bark() method. In the Edexcel specification, you need to be able to identify superclasses and subclasses and understand how inheritance supports polymorphism.

    继承允许一个类(子类)继承另一个类(父类)的属性和方法。这促进了代码复用,并建立了自然的层次结构。例如,Dog 类可以从 Animal 类继承,获得 eat() 等基本方法,同时添加自己的 bark() 方法。在 Edexcel 大纲中,你需要能够识别父类和子类,并理解继承如何支持多态。


    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 often implemented through method overriding, where a subclass provides a specific implementation of a method already defined in its superclass. For instance, both Circle and Rectangle subclasses of a Shape class can have a draw() method, but each draws itself differently. Polymorphism simplifies code that works with objects of a common supertype.

    多态意为“多种形态”,它允许不同类的对象以各自的方式响应相同的方法调用。这通常通过方法重写来实现,即子类提供对父类中已定义方法的具体实现。例如,Shape 类的子类 CircleRectangle 都可以有 draw() 方法,但每个方法绘制自身的方式不同。多态简化了与共同父类型对象交互的代码。


    7. Abstract Classes and Interfaces | 抽象类与接口

    An abstract class is a class that cannot be instantiated directly and is designed to be subclassed. It may contain abstract methods (without implementation) that must be overridden by subclasses. An interface (in languages like Java) defines a contract of methods that implementing classes must fulfil. Both concepts enforce a consistent design and support polymorphism. Edexcel A-Level covers abstract classes as a way to define a common template while leaving specific behaviours to subclasses.

    抽象类是不能直接实例化、专为子类化而设计的类。它可以包含必须在子类中被重写的抽象方法(没有实现)。接口(在 Java 等语言中)定义了实现类必须履行的行为契约。这两个概念都强制了一致的设计,并支持多态。Edexcel A-Level 将抽象类视为定义通用模板、而将特定行为留给子类的一种方式。


    8. Constructor Methods | 构造方法

    A constructor is a special method that is automatically called when an object of a class is created. It is typically used to initialise the object’s attributes. In Python, the constructor is __init__(); in Java, it is a method with the same name as the class. Constructors can be overloaded to accept different sets of parameters, providing flexibility in object creation. Understanding constructors is vital for working with OOP in any language featured in the Edexcel course.

    构造方法是一种特殊方法,在创建类的对象时自动调用。它通常用于初始化对象的属性。在 Python 中,构造方法是 __init__();在 Java 中,它是一个与类同名的方法。构造方法可以重载以接受不同的参数集,从而为对象创建提供灵活性。理解构造方法对于在 Edexcel 课程所涵盖的任何语言中使用 OOP 都至关重要。


    9. Advantages of OOP | 面向对象编程的优点

    OOP offers several benefits: improved code reuse through inheritance, easier maintenance due to modularity, enhanced security with encapsulation, and greater flexibility via polymorphism. It also makes it simpler to map real-world problems to program structures. These advantages explain why OOP is the dominant paradigm in modern software development and why the Edexcel syllabus places significant emphasis on it.

    面向对象编程提供了诸多优点:通过继承提高代码复用性,通过模块化便于维护,通过封装增强安全性,通过多态提高灵活性。它还使得将现实世界问题映射到程序结构变得更加简单。这些优点解释了为什么 OOP 成为现代软件开发中的主导范式,以及为什么 Edexcel 大纲对其给予了高度重视。


    10. OOP in the Edexcel A-Level Curriculum | Edexcel A-Level 课程中的面向对象编程

    The Edexcel A-Level Computer Science specification (2015) includes OOP in Topic 1.7 (Programming Paradigms) and throughout the problem-solving components. Students are expected to define and use classes, implement encapsulation, apply inheritance and polymorphism, and evaluate the suitability of OOP for given scenarios. Practical programming tasks often require designing class diagrams and writing object-oriented code in a language such as Python or Java. Mastering these concepts is not only essential for the written examination but also for the non-exam assessment (NEA) project.

    Edexcel A-Level 计算机科学大纲(2015版)在主题 1.7(编程范式)以及问题解决相关部分中包含了面向对象编程。学生需要定义和使用类、实现封装、应用继承和多态,并评估 OOP 对给定场景的适用性。实践编程任务通常要求设计类图并用 Python 或 Java 等语言编写面向对象代码。掌握这些概念不仅对笔试至关重要,对非考试评估(NEA)项目也是如此。


    11. Key Terminology Summary | 关键术语总结

    Term English Definition 中文释义
    Class Blueprint for objects 类的蓝图
    Object Instance of a class 类的实例
    Encapsulation Bundling data and methods, restricting access 封装数据和方法,限制访问
    Inheritance Deriving a new class from an existing one 从现有类派生新类
    Polymorphism Ability to take many forms; method overriding 多种形态的能力;方法重写
    Abstract Class Class that cannot be instantiated, with abstract methods 无法实例化、含抽象方法的类
    Constructor Special method to initialise objects 用于初始化对象的特殊方法

    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Operating Systems & Programming Interfaces | 操作系统与编程接口

    📚 Operating Systems & Programming Interfaces | 操作系统与编程接口

    Programming at A-Level extends beyond writing algorithms; it requires understanding how software interacts with the underlying hardware through the operating system (OS). The OS provides essential abstractions like processes, memory management, and file systems that directly affect how programs execute. This revision article explores core OS concepts from a programmer’s perspective, focusing on the interfaces that allow user code to request services from the kernel.

    在 A-Level 编程中,不仅要会写算法,还要理解软件如何通过操作系统与底层硬件交互。操作系统提供了进程、内存管理、文件系统等关键抽象,直接影响程序的执行方式。本文从程序员的角度复习操作系统核心概念,重点介绍让用户代码能够请求内核服务的接口。

    1. What Is an Operating System? | 什么是操作系统?

    An operating system is system software that manages computer hardware resources and provides common services for application programs. It acts as an intermediary between the user and the hardware, hiding complexity and offering a uniform programming environment. Key functions include process management, memory management, file system management, and device I/O control.

    操作系统是管理计算机硬件资源并为应用程序提供通用服务的系统软件。它充当用户和硬件之间的中介,隐藏复杂性并提供统一的编程环境。关键功能包括进程管理、内存管理、文件系统管理以及设备 I/O 控制。

    From a programmer’s viewpoint, the OS enables multiple applications to run concurrently without interference. It enforces protection mechanisms, schedules CPU time, and manages virtual memory. Understanding these services is crucial for writing efficient, secure, and portable code.

    从程序员的角度看,操作系统允许多个应用程序并发运行而不相互干扰。它执行保护机制、调度 CPU 时间并管理虚拟内存。理解这些服务对于编写高效、安全和可移植的代码至关重要。


    2. The Role of the OS in Program Execution | 操作系统在程序执行中的作用

    When a program is executed, the OS creates a process—an instance of the program in memory. The OS allocates memory for code, data, stack, and heap segments. It loads the executable file, resolves dynamic libraries, and transfers control to the program’s entry point. The program then runs in user mode, switching to kernel mode via system calls whenever it needs privileged operations.

    当程序执行时,操作系统会创建一个进程——程序在内存中的实例。OS 为代码、数据、堆栈和堆段分配内存。它加载可执行文件,解析动态链接库,并将控制权转移到程序的入口点。程序随后在用户模式下运行,每当需要特权操作时,通过系统调用切换到内核模式。

    The OS also manages the process lifecycle: creation, scheduling, blocking, and termination. Programmers can influence execution by using APIs that trigger these state transitions, such as creating child processes or waiting for I/O completion.

    操作系统还管理进程生命周期:创建、调度、阻塞和终止。程序员可以通过使用触发这些状态转换的 API 来影响执行,例如创建子进程或等待 I/O 完成。


    3. Process Management and Scheduling | 进程管理与调度

    A process consists of a program counter, registers, and memory segments. The OS maintains a process control block (PCB) for each process, storing its state, priority, and accounting information. The scheduler decides which process gets the CPU next, aiming to maximise throughput and minimise response time.

    进程由程序计数器、寄存器和内存段组成。操作系统为每个进程维护一个进程控制块(PCB),存储其状态、优先级和统计信息。调度程序决定哪个进程接下来获得 CPU,旨在最大化吞吐量并最小化响应时间。

    Common scheduling algorithms studied at A-Level include First Come First Served (FCFS), Shortest Job First (SJF), Priority Scheduling, and Round Robin. Programmers rarely implement these directly but experience their effects through process responsiveness and fairness. For example, a CPU-bound process may starve I/O-bound processes under certain policies.

    A-Level 常见的调度算法包括先来先服务(FCFS)、最短作业优先(SJF)、优先级调度和轮转调度(Round Robin)。程序员很少直接实现这些算法,但会通过进程响应性和公平性感受其影响。例如,在某种策略下,CPU 密集型进程可能导致 I/O 密集型进程饥饿。


    4. Memory Management for Programmers | 面向程序员的内存管理

    Memory management involves allocating physical and virtual memory to processes. The OS uses techniques like paging, segmentation, and virtual memory to give each process its own address space. From a programming perspective, dynamic memory allocation (e.g., malloc in C, new in Java) relies on the OS’s heap manager.

    内存管理涉及为进程分配物理和虚拟内存。操作系统使用分页、分段和虚拟内存等技术,为每个进程提供自己的地址空间。从编程的角度看,动态内存分配(如 C 语言的 malloc、Java 的 new)依赖于操作系统的堆管理器。

    Understanding the memory layout—text, data, BSS, heap, and stack—helps in debugging buffer overflows or segmentation faults. Virtual memory allows processes to exceed physical RAM by swapping pages to disk, but excessive paging leads to thrashing, degrading performance. Good programming practices, such as avoiding memory leaks and using appropriate data structures, can minimise memory footprint.

    理解内存布局——文本段、数据段、BSS 段、堆和栈——有助于调试缓冲区溢出或段错误。虚拟内存允许进程通过将页面交换到磁盘来超出物理 RAM,但过度的分页会导致系统颠簸(thrashing),降低性能。良好的编程实践,如避免内存泄漏和使用合适的数据结构,可以最小化内存占用。


    5. File Systems and I/O Operations | 文件系统与输入/输出操作

    The file system provides a logical view of persistent storage. Programmers interact with files via high-level language libraries that ultimately call OS file operations: open, read, write, seek, and close. The OS handles buffering, permission checks, and device drivers.

    文件系统提供了持久存储的逻辑视图。程序员通过高级语言库与文件交互,这些库最终调用操作系统文件操作:open、read、write、seek 和 close。操作系统处理缓冲、权限检查和设备驱动程序。

    In A-Level projects, you may need to read from text files, write binary data, or traverse directories. The OS abstracts differences between storage devices, so the same read() call works whether the file is on a hard disk, SSD, or network drive. Understanding file descriptors and streams is essential for I/O redirection and piping in shell programming.

    在 A-Level 项目中,你可能需要从文本文件读取、写入二进制数据或遍历目录。操作系统抽象了存储设备之间的差异,因此相同的 read() 调用无论文件在硬盘、SSD 还是网络驱动器上都能工作。理解文件描述符和流对于 Shell 编程中的 I/O 重定向和管道至关重要。


    6. System Calls: The Programming Interface | 系统调用:编程接口

    System calls are the programming interface between user-space applications and the kernel. When a program needs a service—such as creating a process, allocating memory, or accessing hardware—it issues a software interrupt or uses a special instruction (e.g., syscall on x86-64). The CPU switches to kernel mode, executes the requested service, and returns the result.

    系统调用是用户空间应用程序与内核之间的编程接口。当程序需要某项服务时——例如创建进程、分配内存或访问硬件——它会发出一个软件中断或使用特殊指令(例如 x86-64 上的 syscall)。CPU 切换到内核模式,执行所请求的服务,并返回结果。

    At A-Level, you are expected to recognise common system calls and their effects. They are typically wrapped in library functions for convenience. For example, the C standard library’s printf() eventually calls the write() system call. Below is a table of important Linux system calls with their descriptions.

    在 A-Level 中,你需要识别常见的系统调用及其效果。它们通常被封装在库函数中以方便使用。例如,C 标准库的 printf() 最终会调用 write() 系统调用。下表列出了重要的 Linux 系统调用及其描述。

    System Call Description
    fork() Creates a new child process by duplicating the calling process.
    execve() Replaces the current process image with a new program.
    wait() / waitpid() Makes the parent process wait for a child to change state.
    open() / read() / write() / close() Manage file I/O operations.
    mmap() Maps files or devices into memory.
    exit() Terminates the calling process.

    中文对应表:fork() 创建新子进程;execve() 用新程序替换当前进程映像;wait()/waitpid() 使父进程等待子进程状态改变;open()/read()/write()/close() 管理文件 I/O;mmap() 将文件或设备映射到内存;exit() 终止调用进程。

    These system calls form the backbone of process and file management in Unix-like systems. In Edexcel exams, you

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Operators and Combined Expressions in A-Level Programming | A-Level编程中的运算符与组合表达式

    📚 Operators and Combined Expressions in A-Level Programming | A-Level编程中的运算符与组合表达式

    In A-Level programming (Edexcel), mastering operators and understanding how they combine within expressions is essential for writing correct and efficient code. Operators are symbols that perform specific operations on one or more operands. When multiple operators appear together in a single expression, the rules of precedence and associativity determine the order of evaluation. This article explores arithmetic, relational, and Boolean operators, shows how they can be combined, and explains the evaluation logic that underpins programs written in languages like Python, Java, or pseudocode.

    在A-Level编程(Edexcel)中,掌握运算符并理解它们在表达式中的组合方式,是写出正确高效代码的基础。运算符是对一个或多个操作数执行特定操作的符号。当多个运算符同时出现在一个表达式中时,优先级和结合性规则决定了求值的顺序。本文探讨算术运算符、关系运算符和布尔运算符,展示它们如何组合,并解释支撑Python、Java或伪代码等语言程序的求值逻辑。


    1. Introduction to Operators | 运算符简介

    Operators are the building blocks of expressions. In programming, we can classify them into arithmetic, relational, and logical categories. Each operator works on data values (operands) and produces a result. For example, the addition operator + adds two numbers, while the comparison operator > checks if one value is greater than another. Understanding the categories helps when constructing combined expressions that mix arithmetic with logical testing.

    运算符是表达式的基本构件。在编程中,我们可以将其分为算术运算符、关系运算符和逻辑运算符几类。每个运算符作用于数据值(操作数)并产生结果。例如,加法运算符 + 将两个数相加,而比较运算符 > 则检查一个值是否大于另一个。理解这些类别有助于构造混合了算术和逻辑测试的组合表达式。


    2. Arithmetic Operators | 算术运算符

    The core arithmetic operators are + (addition), – (subtraction), * (multiplication), / (division), MOD (modulus), and DIV (integer division). These are used to perform mathematical calculations. In many languages, / gives a floating‑point result, while DIV or // (floor division) returns only the whole‑number part. Arithmetic operators form the basis of formulaic expressions that variables store.

    核心算术运算符包括 +(加)、-(减)、*(乘)、/(除)、MOD(取模)和 DIV(整除)。它们用于执行数学计算。在许多语言中,/ 给出浮点结果,而 DIV 或 //(向下取整除法)只返回整数部分。算术运算符构成了变量存储的公式化表达式的基础。


    3. Integer Division and Modulus | 整除与取模

    Integer division discards any remainder, while modulus returns the remainder of a division. For instance, 17 DIV 5 yields 3, and 17 MOD 5 yields 2. These operations are particularly useful in algorithms that need to split quantities, check divisibility, or wrap around array indices. Combined with other arithmetic, they can solve problems like extracting digits from a number.

    整除会丢弃余数,而取模则返回除法运算的余数。例如,17 DIV 5 得 3,17 MOD 5 得 2。这些操作在需要分割数量、检查整除性或循环使用数组索引的算法中特别有用。与其他算术运算结合,它们可以解决诸如从一个数字中提取数位的问题。


    4. Relational (Comparison) Operators | 关系运算符

    Relational operators compare two values and return a Boolean result (TRUE or FALSE). The standard set includes = (equal to), <> or != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to). They are frequently used in selection and iteration statements as conditions that control program flow.

    关系运算符比较两个值并返回布尔结果(TRUE 或 FALSE)。标准集合包括 =(等于)、<> 或 !=(不等于)、<(小于)、>(大于)、<=(小于或等于)和 >=(大于或等于)。它们经常作为控制程序流程的条件出现在选择和迭代语句中。


    5. Boolean Logical Operators | 布尔逻辑运算符

    Boolean operators act on Boolean values and are primary tools for building complex conditions. The fundamental ones are AND, OR, and NOT. In many languages, AND is true only if both operands are true; OR is true if at least one operand is true; NOT simply negates the truth value. Combining relational and logical operators allows the expression of intricate decision logic.

    布尔运算符作用于布尔值,是构建复杂条件的主要工具。基本的运算符有 AND、OR 和 NOT。在许多语言中,AND 只在两个操作数都为真时才为真;OR 只要至少一个操作数为真就为真;NOT 则直接取反真值。将关系运算符与逻辑运算符结合,可以表达复杂的决策逻辑。


    6. Operator Precedence | 运算符优先级

    When an expression contains different types of operator, precedence decides which operation is performed first. Arithmetic operators generally have higher precedence than relational ones, which in turn rank higher than logical operators. Within arithmetic, * / MOD DIV evaluate before + -. A typical precedence order from highest to lowest is: parentheses; arithmetic (unary followed by multiplicative, then additive); relational; NOT; AND; OR.

    当一个表达式包含不同类型的运算符时,优先级决定哪个运算先执行。算术运算符通常比关系运算符优先级高,而关系运算符又优先于逻辑运算符。在算术运算中,* / MOD DIV 先于 + – 求值。典型的优先级从高到低的顺序是:括号;算术(一元,然后是乘除类,再是加减类);关系;NOT;AND;OR。

    Operator 中文 Precedence (high → low)
    ( ) 括号 1 (highest)
    NOT, unary + – 逻辑非/一元正负 2
    * / MOD DIV 乘 除 取模 整除 3
    + – 加 减 4
    < > <= >= = <> 关系比较 5
    AND 逻辑与 6
    OR 逻辑或 7 (lowest)

    Note: exact ordering can vary slightly between languages, so always consult your specification’s pseudocode rules. / 注意:不同语言的确切顺序可能略有不同,请务必参考考纲中的伪代码规则。


    7. Evaluating Combined Expressions | 组合表达式的求值

    A combined expression mixes arithmetic, relational, and logical operators. For example: x + y > 10 AND z < 5. The arithmetic (x + y) is evaluated first, then the relational comparisons (> 10, < 5), and finally the logical AND. Step‑by‑step evaluation ensures that the intention of the condition matches the machine’s interpretation. Misreading precedence can lead to bugs that are hard to spot.

    组合表达式混合了算术、关系与逻辑运算符。例如:x + y > 10 AND z < 5。先计算算术部分 (x + y),再进行关系比较 (> 10, < 5),最后执行逻辑 AND。逐步求值可确保条件的本意与机器的解释相一致。误读优先级可能导致难以发现的错误。


    8. Associativity of Operators | 运算符的结合性

    When two operators of the same precedence appear together, associativity decides the direction of evaluation. Most arithmetic and relational operators are left‑associative, meaning they group from left to right. For instance, a - b - c is evaluated as (a - b) - c. Unary operators and assignment are typically right‑associative. Understanding associativity removes ambiguity in expressions like a / b * c.

    当两个优先级相同的运算符相邻时,结合性决定求值的方向。大多数算术和关系运算符都是左结合的,即从左向右分组。例如,a - b - c 的求值顺序是 (a - b) - c。一元运算符和赋值通常为右结合。理解了结合性,即可消除 a / b * c 这类表达式的歧义。


    9. Using Parentheses to Control Order | 使用括号控制运算顺序

    Parentheses override default precedence and associativity. Any sub‑expression enclosed in ( ) is evaluated first. Even when not strictly needed, adding parentheses can improve readability and prevent logical errors. For example, writing (age >= 18) AND (membership = TRUE) makes the condition clearer than relying solely on precedence. Good programmers use parentheses to make combined expressions self‑documenting.

    括号可以覆盖默认的优先级和结合性。任何用 ( ) 括起来的子表达式都会优先求值。即使在不严格需要的时候,添加括号也能提高可读性,防止逻辑错误。例如,写成 (age >= 18) AND (membership = TRUE) 比单纯依赖优先级更能清晰地表达条件。优秀的程序员会利用括号让组合表达式自带说明性。


    10. Common Pitfalls with Combined Operators | 组合运算符的常见陷阱

    • Confusing = for ==: In many languages, = is assignment while == is equality test. Using = inside a condition often leads to a logical error or an unintended assignment. / 混淆 = 与 ==:在许多语言中,= 是赋值,== 才是相等测试。在条件中使用 = 常常导致逻辑错误或意外的赋值。
    • Mixing AND/OR without parentheses: Without parentheses, AND binds tighter than OR, so a OR b AND c means a OR (b AND c). This may not be what the programmer intended. / 不使用括号混用 AND/OR:在没有括号的情况下,AND 比 OR 结合得更紧密,因此 a OR b AND c 实际上相当于 a OR (b AND c),这可能并非程序员的本意。
    • Assuming left‑to‑right for all operators: Not all operators are left‑associative. Exponent, unary, and assignment operators often associate right‑to‑left. / 假设所有运算符都从左到右:并非所有运算符都是左结合。指数、一元和赋值运算符常常从右到左结合。
    • Integer division truncation: In some languages, dividing two integers with / performs integer division, discarding the remainder. This can silently affect combined expressions. / 整除截断:在某些语言中,使用 / 对两个整数相除会执行整除并丢弃余数,这可能会悄然影响组合表达式的结果。

    11. Practice Examples | 练习示例

    Consider the following pseudocode and evaluate step by step. / 考虑下面的伪代码,逐步求值。

    result ← (5 + 3 * 2) > 10 AND NOT (4 <= 2)

    Step 1: inside first parentheses, multiplication has precedence: 3 * 2 = 6; then 5 + 6 = 11. / 第一步:第一对括号内乘法优先:3 * 2 = 6;然后 5 + 6 = 11。

    Step 2: relational comparison: 11 > 10 is TRUE. / 第二步:关系比较:11 > 10 为 TRUE。

    Step 3: second parentheses: 4 <= 2 is FALSE. / 第三步:第二对括号:4 <= 2 为 FALSE。

    Step 4: NOT FALSE gives TRUE. / 第四步:NOT FALSE 得 TRUE。

    Step 5: TRUE AND TRUE yields TRUE. / 第五步:TRUE AND TRUE 结果为 TRUE。

    Thus the variable result holds TRUE. / 因此变量 result 的值为 TRUE。

    Another example: total ← price * quantity + delivery. If price=10, quantity=3, delivery=5, the multiplication 10 * 3 = 30 happens first, then 30 + 5 = 35. Adding parentheses like price * (quantity + delivery) would change the outcome to 10 * 8 = 80, demonstrating how order matters. / 另一个例子:total ← price * quantity + delivery。若 price=10, quantity=3, delivery=5,首先计算乘法 10 * 3 = 30,然后 30 + 5 = 35。如加上括号变成 price * (quantity + delivery),结果将变为 10 * 8 = 80,这体现了顺序的重要性。


    12. Conclusion | 结论

    Operators form the nervous system of programming logic. A solid grasp of arithmetic, relational, and Boolean operators, together with the rules of precedence, associativity, and the careful use of parentheses, empowers you to write clear, predictable code. In A-Level exams, you will be expected to trace through combined expressions and construct conditions without ambiguity. Regular practice with mixed-operator expressions will build the confidence to handle any programming challenge.

    运算符构成了编程逻辑的神经系统。牢牢掌握算术、关系和布尔运算符,并熟悉优先级、结合性规则以及谨慎使用括号,能让你写出清晰、可预测的代码。在A-Level考试中,你需要能够追踪组合表达式的求值过程,并构建无歧义的条件。通过经常练习混合运算符的表达式,你将培养出应对任何编程挑战的信心。


    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Operating Systems: Process Management and Scheduling | 操作系统:进程管理与调度

    📚 Operating Systems: Process Management and Scheduling | 操作系统:进程管理与调度

    An operating system (OS) is the fundamental software that manages computer hardware and provides services for application programs. In A‑Level Computer Science, understanding how the OS handles processes and schedules CPU time is critical. This article explores the key concepts of process management and scheduling algorithms, essential for Edexcel exam success.

    操作系统是管理计算机硬件并为应用程序提供服务的底层软件。在A‑Level计算机科学中,理解操作系统如何处理进程以及调度CPU时间是至关重要的。本文探讨进程管理和调度算法的核心概念,这对Edexcel考试成功至关重要。

    1. What is an Operating System? | 什么是操作系统?

    An operating system acts as an intermediary between the user and the computer hardware. Its main roles include resource management (CPU, memory, I/O devices), process management, file system management, and providing a user interface. Without an OS, applications would need to directly control hardware, making software development extremely complex.

    操作系统充当用户与计算机硬件之间的中介。它的主要职责包括资源管理(CPU、内存、I/O设备)、进程管理、文件系统管理以及提供用户界面。如果没有操作系统,应用程序将需要直接控制硬件,使得软件开发极其复杂。


    2. The Concept of a Process | 进程的概念

    A process is a program in execution. It is more than just the program code; it includes the current activity, as represented by the program counter, processor registers, and memory addresses. A process can be in one of several states as it runs and waits for events.

    进程是正在执行的程序。它不仅仅是程序代码,还包括当前活动,由程序计数器、处理器寄存器和内存地址表示。进程在运行和等待事件时可能处于多种状态之一。


    3. Process States and Transitions | 进程状态及其转换

    The typical process states are: New (being created), Ready (waiting to be assigned to a processor), Running (instructions are being executed), Waiting/Blocked (waiting for some event, such as I/O completion), and Terminated (finished execution). Transitions occur when a process is scheduled, issues an I/O request, or is interrupted.

    典型的进程状态有:新建(正在创建)、就绪(等待分配处理器)、运行(正在执行指令)、等待/阻塞(等待某事件,如I/O完成)和终止(执行完毕)。状态转换发生在进程被调度、发出I/O请求或被中断时。


    4. Process Control Block (PCB) | 进程控制块

    Each process is represented in the OS by a Process Control Block (PCB). It contains process ID, program counter, CPU registers, memory management information, scheduling information (priority, pointer to queue), and I/O status. The PCB is saved and restored during context switches.

    每个进程在操作系统中由一个进程控制块(PCB)表示。它包含进程ID、程序计数器、CPU寄存器、内存管理信息、调度信息(优先级、队列指针)以及I/O状态。在进行上下文切换时,PCB被保存和恢复。


    5. Scheduling Queues | 调度队列

    The OS maintains various queues for process scheduling: the job queue holds all processes in the system; the ready queue contains processes residing in main memory, ready to run; and device queues hold processes waiting for an I/O device. These queues are typically linked lists.

    操作系统维护各种用于进程调度的队列:作业队列包含系统中的所有进程;就绪队列包含驻留在主存中、准备运行的进程;设备队列包含等待I/O设备的进程。这些队列通常是链表。


    6. CPU Scheduling Criteria | CPU调度标准

    Scheduling algorithms are evaluated using criteria such as CPU utilisation (keep CPU busy), throughput (number of processes completed per unit time), turnaround time (time from submission to completion), waiting time (time spent in ready queue), and response time (time from submission to first response).

    调度算法的评估标准包括CPU利用率(保持CPU忙碌)、吞吐量(单位时间完成的进程数)、周转时间(从提交到完成的时间)、等待时间(在就绪队列中花费的时间)以及响应时间(从提交到首次响应的时间)。


    7. First-Come, First-Served (FCFS) | 先来先服务调度

    FCFS is the simplest scheduling algorithm. The process that requests the CPU first is allocated the CPU first. It is implemented using a FIFO queue. However, it can lead to the convoy effect, where short processes wait behind long processes, increasing average waiting time.

    FCFS是最简单的调度算法。最先请求CPU的进程最先获得CPU。它使用FIFO队列实现。然而,它可能导致护航效应,即短进程等待在长进程后面,增加平均等待时间。

    Example: P1 burst=24, P2 burst=3, P3 burst=3. If order is P1, P2, P3, waiting times: P1=0, P2=24, P3=27; average = 17. If order P2, P3, P1, average = 3. This shows how FCFS is sensitive to arrival order.

    例如:P1爆发时间=24,P2=3,P3=3。如果顺序是P1、P2、P3,等待时间:P1=0,P2=24,P3=27;平均=17。如果顺序P2、P3、P1,平均=3。表明FCFS对到达顺序敏感。


    8. Shortest Job First (SJF) | 最短作业优先调度

    SJF selects the process with the smallest next CPU burst. It is optimal in minimising average waiting time. SJF can be preemptive or non‑preemptive. Preemptive SJF (Shortest Remaining Time First) preempts if a new process arrives with a shorter burst than the remaining time of the current process.

    SJF选择下一次CPU爆发时间最短的进程。它在最小化平均等待时间方面是最优的。SJF可以是抢占式或非抢占式。抢占式SJF(最短剩余时间优先)如果新到达进程的爆发时间比当前进程剩余时间更短,则抢占。

    SJF requires knowledge of future burst lengths. Usually, predicted using exponential averaging. The prediction formula is:

    τₙ₊₁ = α tₙ + (1 − α) τₙ

    where tₙ is the actual CPU burst, τₙ is the predicted burst, and α is a weight factor (0 ≤ α ≤ 1). This prediction enables the scheduler to approximate SJF.

    SJF需要知道未来的爆发长度,通常使用指数平均进行预测。预测公式为:

    τₙ₊₁ = α tₙ + (1 − α) τₙ

    其中tₙ是实际CPU爆发时间,τₙ是预测值,α是权重因子(0 ≤ α ≤ 1)。此预测使调度器能够近似实现SJF。


    9. Priority Scheduling | 优先级调度

    A priority is associated with each process, and the CPU is allocated to the process with the highest priority. Priorities can be static or dynamic. Priority scheduling can be preemptive or non‑preemptive. A major problem is starvation, where low‑priority processes may never execute.

    每个进程关联一个优先级,CPU分配给最高优先级的进程。优先级可以是静态或动态的。优先级调度可以是抢占式或非抢占式。一个主要问题是饥饿,即低优先级进程可能永远无法执行。

    Solution: aging – gradually increase the priority of waiting processes over time. Eventually, even a low‑priority process will attain high priority and be executed.

    解决方案:老化——随时间逐渐增加等待进程的优先级。最终,即使低优先级进程也会获得高优先级并执行。


    10. Round Robin Scheduling | 轮转调度

    Round Robin (RR) is designed for time‑sharing systems. Each process gets a small unit of CPU time called a time quantum (typically 10‑100 ms). After a quantum, if the process is still running, it is preempted and added to the tail of the ready queue. RR provides good response time and fairness.

    轮转调度(RR)专为分时系统设计。每个进程获得一小段CPU时间,称为时间片(通常10‑100毫秒)。一个时间片后,如果进程仍在运行,它被抢占并添加到就绪队列尾部。RR提供了良好的响应时间和公平性。

    Performance depends on quantum size: small quantum leads to many context switches, increasing overhead; large quantum degrades to FCFS. A rule of thumb: 80% of CPU bursts should be shorter than the quantum.

    性能取决于时间片大小:小时间片导致许多上下文切换,增加开销;大时间片退化为FCFS。经验法则:80%的CPU爆发应短于时间片。


    11. Multilevel Queue Scheduling | 多级队列调度

    Processes are partitioned into groups (e.g., interactive, batch) with different response‑time requirements. Each group has its own queue and its own scheduling algorithm. For example, foreground queue uses RR, background queue uses FCFS. Scheduling among queues can be fixed‑priority preemptive or time‑sliced.

    进程被划分为具有不同响应时间要求的组(例如交互式、批处理)。每个组有自己的队列和自己的调度算法。例如,前台队列使用RR,后台队列使用FCFS。队列之间的调度可以是固定优先级抢占式或时间片划分。


    12. Context Switching | 上下文切换

    Switching the CPU from one process to another requires saving the state (PCB) of the old process and loading the saved state of the new process. This is called a context switch. It is pure overhead, as the system does no useful work while switching. The time depends on hardware support (e.g., multiple register sets).

    将CPU从一个进程切换到另一个进程需要保存旧进程的状态(PCB)并加载新进程的已保存状态。这称为上下文切换。它是纯粹的开销,因为系统在切换时不执行任何有用工作。时间取决于硬件支持(例如多组寄存器)。

    Frequent

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Operating Systems: Processes and CPU Scheduling | 操作系统:进程与CPU调度

    📚 Operating Systems: Processes and CPU Scheduling | 操作系统:进程与CPU调度

    An operating system (OS) is the fundamental software that manages hardware and software resources, providing a stable environment for applications to run. For A-Level Computer Science, understanding how the OS handles processes and schedules CPU time is essential — it underpins everything from multitasking to responsiveness in real-time systems. This article explores key concepts: process states, the Process Control Block, context switching, and a range of scheduling algorithms such as FCFS, SJF, Round Robin, and priority-based methods.

    操作系统(OS)是管理硬件和软件资源的基础软件,为应用程序提供稳定的运行环境。对于A-Level计算机科学而言,理解操作系统如何处理进程以及如何调度CPU时间至关重要——这构成了从多任务处理到实时系统响应能力的一切基础。本文将探讨核心概念:进程状态、进程控制块、上下文切换,以及一系列调度算法,例如先来先服务、短作业优先、轮转调度和基于优先级的方法。


    1. Introduction to Operating Systems | 操作系统简介

    An operating system acts as an intermediary between the user and the computer hardware. It hides the complexity of hardware by providing a set of services and a user interface. Key examples include Windows, Linux, macOS, and real-time operating systems (RTOS) used in embedded devices. Without an OS, every application would need to directly control the hardware, leading to chaos and massive duplication of effort.

    操作系统充当用户与计算机硬件之间的中介。它通过提供一组服务和用户界面来隐藏硬件的复杂性。典型的例子包括Windows、Linux、macOS,以及用于嵌入式设备的实时操作系统(RTOS)。如果没有操作系统,每个应用程序都必须直接控制硬件,这会导致混乱和大量的重复工作。


    2. Functions of an Operating System | 操作系统的功能

    The OS performs several critical functions: process management, memory management, file system management, I/O device management, security and access control, and networking. In this article we focus on process management — how the OS creates, schedules, and terminates processes, and how it allocates the CPU among them using various scheduling algorithms.

    操作系统执行若干关键功能:进程管理、内存管理、文件系统管理、I/O设备管理、安全与访问控制以及网络功能。在本文中,我们着重讨论进程管理——操作系统如何创建、调度和终止进程,以及如何运用各种调度算法在它们之间分配CPU时间。


    3. What is a Process? | 什么是进程?

    A process is a program in execution. While a program is a passive set of instructions stored on disk, a process is an active entity with its own memory space, program counter, registers, and execution context. Modern operating systems are multiprogramming, meaning several processes can reside in memory simultaneously, competing for the CPU. The OS must ensure fair, efficient, and safe sharing of the processor.

    进程是正在运行的程序。程序是存储在磁盘上的一组被动指令,而进程是一个活跃的实体,拥有自己的内存空间、程序计数器、寄存器和执行上下文。现代操作系统都是多道程序设计的,这意味着多个进程可以同时驻留在内存中,竞争CPU资源。操作系统必须确保处理器的共享是公平、高效且安全的。


    4. Process States | 进程状态

    During its lifetime, a process moves through several discrete states. The classic five-state model includes: New (process being created), Ready (waiting to be assigned to the CPU), Running (instructions are being executed), Blocked (or Waiting, waiting for an event such as I/O completion), and Terminated (finished execution). The transitions between states are triggered by events like interrupts or I/O requests.

    在其生命周期中,进程会经历几个离散的状态。经典的五状态模型包括:新建(进程正在创建)、就绪(等待被分配CPU)、运行(正在执行指令)、阻塞(或等待,例如等待I/O完成)和终止(执行完毕)。状态之间的转换由中断或I/O请求等事件触发。


    5. Process Control Block (PCB) | 进程控制块

    To manage a process, the OS maintains a data structure called the Process Control Block (PCB). The PCB contains all information needed to track and resume the process: process ID (PID), program counter (PC), CPU registers, memory limits, list of open files, and the process state. When a context switch occurs, the OS saves the current PCB and loads the PCB of the next process, allowing seamless multitasking.

    为了管理进程,操作系统维护一个称为进程控制块(PCB)的数据结构。PCB包含了追踪和恢复进程所需的所有信息:进程ID(PID)、程序计数器(PC)、CPU寄存器、内存界限、打开文件列表以及进程状态。当发生上下文切换时,操作系统保存当前PCB并加载下一个进程的PCB,从而实现无缝的多任务处理。


    6. Introduction to CPU Scheduling | CPU调度简介

    CPU scheduling determines which process in the ready queue gets the CPU next. The scheduler aims to maximise CPU utilisation and throughput, minimise turnaround time, waiting time, and response time. Scheduling algorithms can be non-preemptive (once a process gets the CPU, it keeps it until it voluntarily releases it) or preemptive (the OS can force a process off the CPU, typically via a timer interrupt).

    CPU调度决定就绪队列中哪个进程下一个获得CPU。调度程序的目标是最大化CPU利用率和吞吐量,最小化周转时间、等待时间和响应时间。调度算法可以是非抢占式的(一旦进程获得CPU,它将一直保持直到自愿释放)或抢占式的(操作系统可以强制进程离开CPU,通常是通过定时器中断)。


    7. First-Come, First-Served (FCFS) | 先来先服务

    FCFS is the simplest scheduling algorithm: processes are executed in the order they arrive. Implementation is straightforward using a FIFO queue. However, FCFS suffers from the ‘convoy effect’ — a long CPU-bound process can hold up a queue of short I/O-bound processes, leading to poor average waiting time. It is non-preemptive and typically not used as a stand-alone scheduler in modern interactive systems.

    FCFS是最简单的调度算法:进程按照到达的顺序执行。使用FIFO队列实现起来非常直接。但是,FCFS存在“护航效应”的问题——一个长CPU密集型进程可能会阻塞一队短的I/O密集型进程,导致平均等待时间很差。它是非抢占式的,在现代交互式系统中通常不会作为独立调度器使用。


    8. Shortest Job First (SJF) | 短作业优先

    SJF selects the process with the smallest total expected CPU burst time. It can be non-preemptive or preemptive (Shortest Remaining Time First, SRTF). SJF is provably optimal in terms of minimising average waiting time for a given set of processes. The drawback is that it requires knowing in advance the length of the next CPU burst, which is rarely possible. Ageing techniques can be used to prevent long jobs from starving.

    SJF选择具有最小预期CPU执行总时间的进程。它可以是非抢占式或抢占式的(最短剩余时间优先,SRTF)。可以证明,对于给定的一组进程,SJF在最小化平均等待时间方面是最优的。其缺点是需要提前知道下一次CPU执行的长度,而这几乎是不可能的。可以使用老化技术来防止长作业饥饿。


    9. Round Robin (RR) | 轮转调度

    Round Robin is a preemptive algorithm designed for time-sharing systems. Each process is given a small fixed unit of CPU time called a time quantum (typically 10–100 ms). If a process does not finish within its quantum, it is preempted and placed at the end of the ready queue. RR ensures fair CPU distribution and guarantees a low response time. Performance depends heavily on the size of the quantum: too small causes excessive context switches, too large degenerates to FCFS.

    轮转调度是一种为分时系统设计的抢占式算法。每个进程被分配一个固定的CPU时间片,称为时间量子(通常为10–100毫秒)。如果进程在其量子内未完成,它会被抢占并放回就绪队列末尾。RR确保了CPU分配的公平性,并保证了较低的响应时间。其性能严重依赖于量子的大小:太小会导致过多的上下文切换,太大则会退化为FCFS。


    10. Priority Scheduling | 优先级调度

    Priority scheduling associates a priority value (integer) with each process. The CPU is allocated to the highest-priority ready process. This can be preemptive or non-preemptive. A major problem is starvation, where low-priority processes may never execute. This is often solved by ‘ageing’, i.e. gradually increasing the priority of a waiting process. Real-world systems often combine priority with other algorithms, e.g. a preemptive priority system where same-priority processes are scheduled RR.

    优先级调度为每个进程关联一个优先级值(整数)。CPU分配给具有最高优先级的就绪进程。这可以是抢占式或非抢占式的。一个主要问题是饥饿,即低优先级的进程可能永远无法执行。这通常通过“老化”来解决,即逐渐提高等待进程的优先级。实际系统常常将优先级与其他算法相结合,例如在一个抢占式优先级系统中,相同优先级的进程按RR进行调度。


    11. Multilevel Queue Scheduling | 多级队列调度

    In multilevel queue scheduling, the ready queue is partitioned into several separate queues, each with its own scheduling algorithm. Processes are permanently assigned to a queue based on properties like memory size, priority, or process type (foreground interactive vs background batch). For example, a foreground queue might use RR for good interactivity, while a background queue might use FCFS. Scheduling among queues is usually done via fixed-priority preemptive or time-sliced allocation.

    在多级队列调度中,就绪队列被划分为几个独立的队列,每个队列有自己的调度算法。进程根据内存大小、优先级或进程类型(前台交互式与后台批处理)等属性被永久分配到一个队列。例如,前台队列可能使用RR以获得良好的交互性,而后台队列则使用FCFS。队列之间的调度通常通过固定优先级抢占或时间片分配来完成。


    12. Scheduling in Real-Time Systems | 实时系统调度

    Real-time systems (RTS) must guarantee that critical tasks complete within strict time constraints. Scheduling algorithms such as Rate Monotonic (RM) and Earliest Deadline First (EDF) are used. In RM, processes with shorter periods are given higher priority (static priority). EDF is a dynamic preemptive scheme where the process closest to its deadline gets the CPU. These algorithms prioritise predictability over fairness, and they require careful analysis of task execution times.

    实时系统必须保证关键任务在严格的时间限制内完成。常用的调度算法包括单调速率调度(RM)和最早截止时间优先(EDF)。RM中,周期越短的进程优先级越高(静态优先级)。EDF是一种动态抢占式方案,最接近其截止时间的进程获得CPU。这些算法将可预测性置于公平性之上,并且需要对任务执行时间进行仔细分析。

    Published by TutorHao | Computer Science Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming: Core Concepts | 面向对象编程核心概念

    📚 Object-Oriented Programming: Core Concepts | 面向对象编程核心概念

    Object-oriented programming (OOP) is a paradigm that organises software around objects containing data and methods, promoting modularity and reusability. It models real-world entities and their interactions, forming the foundation of many modern languages like Java, C++, and Python. This article explains the core OOP concepts as required for A-Level Edexcel Computer Science, including classes, objects, encapsulation, inheritance, polymorphism, and more.

    面向对象编程(OOP)是一种根据包含数据和方法的对象来组织软件的范式,能提升模块化和可复用性。它对现实世界实体及其交互进行建模,是 Java、C++、Python 等现代语言的基石。本文讲解 A-Level Edexcel 计算机科学所需的 OOP 核心概念,包括类、对象、封装、继承、多态等。


    1. Programming Paradigms | 编程范式概述

    Programming paradigms are fundamental styles of programming that provide a way of thinking about code structure. The two main paradigms are procedural and object-oriented. In procedural programming, the program is split into procedures or functions; in OOP, it is split into objects. OOP models real-world entities more naturally.

    编程范式是编程的基本风格,提供了一种思考代码结构的方式。两大范式是过程式与面向对象。过程式编程将程序划分为过程或函数;而 OOP 则划分为对象。OOP 能更自然地模拟现实世界实体。


    2. Classes and Objects | 类与对象

    A class is a blueprint or template that defines the attributes (data) and methods (behaviour) common to all objects of a certain kind. An object is an instance of a class; it holds specific values for the attributes and can execute the defined methods. For example, a class Car might have attributes make, model, speed and methods accelerate(), brake(). An object myCar would have actual values like ‘Toyota’, ‘Corolla’, 0.

    类是定义某一类对象共有属性(数据)和方法(行为)的蓝图或模板。对象是类的实例,持有属性的具体值,并能执行定义的方法。例如,类 Car 可能有属性 makemodelspeed 和方法 accelerate()brake()。对象 myCar 则具有实际值,如 ‘Toyota’、’Corolla’、0。


    3. Encapsulation and Data Hiding | 封装与数据隐藏

    Encapsulation bundles attributes and methods inside a class and restricts direct access to some of an object’s components. This is often implemented by declaring attributes as private and providing public getter and setter methods. It protects data integrity and reduces coupling between modules.

    封装将属性和方法捆绑在类内部,并限制对对象某些组件的直接访问。通常通过将属性声明为私有、并公开 getter 和 setter 方法来实现。它能保护数据完整性并降低模块间的耦合度。


    4. Inheritance | 继承

    Inheritance allows a new class (subclass) to acquire the properties and methods of an existing class (superclass). This promotes code reuse and establishes a hierarchical relationship. For example, a SportsCar subclass could inherit from Car and add a turboBoost() method. Edexcel often tests single inheritance and the ‘is-a’ relationship.

    继承允许新类(子类)获取已有类(超类)的属性和方法。这促进了代码复用并建立层次关系。例如,SportsCar 子类可继承自 Car,并添加 turboBoost() 方法。Edexcel 常考单继承和 “is-a” 关系。


    5. Polymorphism | 多态

    Polymorphism means ‘many forms’. In OOP, it allows objects of different classes to be treated as objects of a common superclass. The most common form is method overriding, where a subclass provides a specific implementation of a method already defined in its superclass. This enables dynamic method dispatch at runtime.

    多态意为“多种形态”。在 OOP 中,它允许将不同类的对象当作共同超类的对象来处理。最常见的形式是方法重写,即子类为其超类中已定义的方法提供特定实现。这使得在运行时能进行动态方法分派。


    6. Abstract Classes and Interfaces | 抽象类与接口

    An abstract class cannot be instantiated; it serves as a base class that defines a common interface for subclasses. It may contain both abstract methods (without implementation) and concrete methods. An interface is a contract that lists method signatures without any implementation. Classes implement interfaces to guarantee certain behaviours. Java and C# distinguish between abstract classes and interfaces, while C++ uses pure virtual functions.

    抽象类不能实例化;它作为基类为子类定义公共接口,可包含抽象方法(无实现)和具体方法。接口是一种契约,仅列出方法签名而不提供实现。类通过实现接口来保证特定行为。Java 和 C# 区分抽象类与接口,C++ 使用纯虚函数。


    7. Association, Aggregation, and Composition | 关联、聚合与组合

    Objects can be related through association, a general connection between classes. Aggregation is a ‘has-a’ relationship where one class contains a reference to another, but the contained object can exist independently (e.g., a library has books). Composition is a stronger ‘part-of’ relationship where the contained object’s lifecycle depends on the container (e.g., a house is composed of rooms).

    对象可通过关联(类之间的一般连接)相互联系。聚合是一种“has-a”关系,一个类包含对另一个类的引用,但被包含对象可独立存在(例如图书馆有书)。组合是更强的“part-of”关系,被包含对象的生命周期依赖容器(例如房子由房间组成)。


    8. Method Overloading | 方法重载

    Method overloading is a form of compile-time polymorphism where multiple methods have the same name but different parameter lists (number, types, or order). This improves code readability and allows similar operations to be performed with different inputs. For instance, add(int a, int b) and add(double a, double b).

    方法重载是编译时多态的一种形式,即多个方法同名但参数列表不同(数量、类型或顺序)。这提高了代码可读性,允许用不同输入执行相似操作。例如 add(int a, int b)add(double a, double b)


    9. Access Modifiers | 访问修饰符

    Access modifiers control the visibility of class members. Common modifiers are public (accessible everywhere), private (only within the same class), and protected (accessible within the package and subclasses). These enforce encapsulation and safeguard sensitive data.

    访问修饰符控制类成员的可见性。常见的有 public(全局可访问)、private(仅在同一类内)和 protected(包内及子类可访问)。它们强制封装并保护敏感数据。


    10. Constructors and Destructors | 构造函数与析构函数

    A constructor is a special method that initialises a new object. It typically has the same name as the class and no return type. Overloaded constructors allow different initialisation scenarios. A destructor (or garbage collector in some languages) cleans up when an object is destroyed.

    构造函数是初始化新对象的特殊方法,通常与类同名、无返回类型。重载构造函数支持不同的初始化方式。析构函数(或某些语言中的垃圾收集器)在对象销毁时进行清理。


    11. OOP Design Principles (SOLID) | 面向对象设计原则 (SOLID)

    While not always tested explicitly, understanding SOLID principles can deepen OOP knowledge. SOLID stands for: Single responsibility, Open/closed, Liskov substitution, Interface segregation, and Dependency inversion. These guide developers to create maintainable, scalable systems.

    尽管不常直接考查,理解 SOLID 原则能加深 OOP 认识。SOLID 代表:单一职责、开闭原则、里氏替换、接口隔离和依赖反转。它们指导开发者构建可维护、可扩展的系统。


    12. Advantages and Disadvantages of OOP | 面向对象的优缺点

    Advantages include modularity, reusability, easier maintenance, and natural modelling. Disadvantages may be increased complexity for small programs, steeper learning curves, and potential performance overhead due to indirection. Edexcel expects candidates to evaluate these trade-offs.

    优点包括模块化、可复用性、易维护和自然建模。缺点可能是对小程序增加复杂度、学习曲线较陡、以及由间接调用造成的潜在性能开销。Edexcel 期望考生能评估这些取舍。


    Published by TutorHao | Computer Science Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Process Scheduling Algorithms in Operating Systems | 操作系统中的进程调度算法

    📚 Process Scheduling Algorithms in Operating Systems | 操作系统中的进程调度算法

    Process scheduling is a fundamental concept in operating systems that determines the order in which processes are executed by the CPU. It directly affects system performance, responsiveness, and fairness. Whether you are writing a simple script or building a complex multitasking application, understanding how the underlying scheduler works helps you write more efficient and predictable code. In this article, we explore the major CPU scheduling algorithms, their implementation, and their trade-offs, aligning with the Edexcel A‑level Computer Science specification.

    进程调度是操作系统中的一个基本概念,它决定了 CPU 执行进程的顺序。调度策略直接影响系统性能、响应速度和公平性。无论你是在写简单脚本还是构建复杂的多任务应用,理解底层调度器的工作原理都有助于编写更高效、更可预测的代码。本文将探讨几种主要的 CPU 调度算法、它们的实现以及各自的权衡,内容与 Edexcel A‑level 计算机科学大纲保持一致。

    1. The Role of the CPU Scheduler | CPU 调度器的角色

    The CPU scheduler is a component of the operating system that selects one process from the ready queue and allocates the CPU to it. The scheduler runs whenever the CPU becomes idle, or when a running process voluntarily yields the CPU (e.g., waiting for I/O). There are two main types of scheduling: preemptive, where the OS can forcibly take the CPU away from a process, and non‑preemptive, where a process keeps the CPU until it voluntarily releases it.

    CPU 调度器是操作系统的一个组件,它从就绪队列中选择一个进程并将 CPU 分配给它。每当 CPU 空闲,或者正在运行的进程主动让出 CPU(例如等待 I/O)时,调度器就会运行。调度主要分为两类:抢占式——操作系统可以强制从进程手中夺走 CPU,以及非抢占式——进程会一直占用 CPU 直到主动释放。


    2. First‑Come, First‑Served (FCFS) | 先来先服务 (FCFS)

    FCFS is the simplest scheduling algorithm: the process that arrives first gets the CPU first. It is implemented using a FIFO queue. While easy to understand, FCFS can lead to the “convoy effect”, where short processes get stuck behind long CPU‑bound processes, resulting in high average waiting time. FCFS is inherently non‑preemptive.

    FCFS 是最简单的调度算法:最先到达的进程最先获得 CPU。它使用先进先出队列来实现。虽然容易理解,但 FCFS 会导致“护航效应”,即短进程被长 CPU 密集型进程阻塞,造成较高的平均等待时间。FCFS 本质上是一种非抢占式算法。


    3. Shortest Job First (SJF) | 最短作业优先 (SJF)

    SJF selects the process with the smallest CPU burst time from the ready queue. This algorithm can be either non‑preemptive (once a process starts, it runs to completion) or preemptive (if a new shorter job arrives, the current job is preempted). SJF theoretically minimises average waiting time, but it requires knowing the burst time of each process in advance, which is usually impossible in practice.

    SJF 从就绪队列中选择 CPU 执行时间最短的进程。该算法可以是非抢占式的(一旦进程开始就运行到结束),也可以是抢占式的(如果有更短的作业到达,当前作业会被抢占)。理论上 SJF 可以最小化平均等待时间,但它需要提前知道每个进程的执行时间,这在实际中通常无法做到。


    4. Shortest Remaining Time First (SRTF) | 最短剩余时间优先 (SRTF)

    SRTF is the preemptive version of SJF. Whenever a new process arrives, the scheduler compares its remaining CPU burst with the remaining time of the currently executing process. If the new process has a shorter remaining time, the CPU is preempted. SRTF can provide even lower average waiting times than non‑preemptive SJF, but it increases context‑switching overhead and still requires burst‑time prediction.

    SRTF 是 SJF 的抢占式版本。每当新进程到达时,调度器会比较其剩余 CPU 执行时间和当前执行进程的剩余时间。如果新进程剩余时间更短,CPU 就会被抢占。SRTF 的平均等待时间可能比非抢占式 SJF 更低,但它增加了上下文切换开销,并且仍然需要预测执行时间。


    5. Round Robin (RR) | 轮转调度 (RR)

    Round Robin is designed for time‑sharing systems. Each process gets a small unit of CPU time called a time quantum (or time slice); after that quantum expires, the process is preempted and placed at the end of the ready queue. RR is fair and prevents starvation, but performance heavily depends on the length of the time quantum. Too large a quantum makes RR behave like FCFS; too small a quantum leads to excessive context switches.

    轮转调度是为分时系统设计的。每个进程获得一小段 CPU 时间,称为时间片;时间片用完后,进程被抢占并放到就绪队列末尾。RR 很公平,能防止饥饿,但性能高度依赖时间片的长度。时间片过大,RR 表现得像 FCFS;时间片过小,又会导致过多的上下文切换。


    6. Priority Scheduling | 优先级调度

    Each process is assigned a priority (often an integer); the CPU is allocated to the process with the highest priority. Priority scheduling can be preemptive or non‑preemptive. A major problem is starvation, where low‑priority processes may never execute if high‑priority processes keep arriving. This can be solved by aging, which gradually increases the priority of waiting processes.

    每个进程被赋予一个优先级(通常是一个整数);CPU 分配给优先级最高的进程。优先级调度可以是抢占式或非抢占式。一个主要问题是饥饿——如果高优先级进程源源不断地到来,低优先级进程可能永远得不到执行。可以通过老化(aging)技术来解决,即逐渐增加等待进程的优先级。


    7. Multilevel Queue Scheduling | 多级队列调度

    Processes are partitioned into several separate queues, typically based on process type (e.g., interactive, batch, system). Each queue has its own scheduling algorithm, and there is also scheduling among the queues (e.g., fixed‑priority preemptive scheduling). This approach allows the system to give different treatment to different categories of processes, but it can be inflexible because a process is permanently assigned to a queue.

    进程被划分到多个独立的队列中,通常根据进程类型(如交互式、批处理、系统)划分。每个队列有自己的调度算法,并且队列之间也有调度(例如固定优先级抢占式调度)。这种方法允许系统对不同类别的进程区别对待,但不够灵活,因为进程被永久分配到某个队列。


    8. Multilevel Feedback Queue (MLFQ) | 多级反馈队列 (MLFQ)

    MLFQ addresses the inflexibility of multilevel queues by allowing processes to move between queues. Typically, it gives shorter time quanta to higher‑priority queues and longer quanta to lower‑priority queues. Processes that use up their time quantum are demoted to a lower‑priority queue; processes that wait too long are promoted. MLFQ approximates SJF without requiring burst‑time knowledge, and it prevents starvation through aging. It is widely used in modern operating systems like Windows and macOS.

    MLFQ 通过允许进程在队列之间移动解决了多级队列的不灵活性。通常,它为高优先级队列分配较短的时间片,为低优先级队列分配较长的时间片。用完时间片的进程会被降级到更低优先级的队列;等待过久的进程则会被提升。MLFQ 无需预知执行时间就能近似 SJF,并且通过老化防止饥饿。它被广泛应用于现代操作系统,如 Windows 和 macOS。


    9. Real‑Time Scheduling | 实时调度

    Real‑time systems require strict timing guarantees. Two common approaches are Rate Monotonic Scheduling (RMS), where static priorities are assigned based on the period of tasks (shorter period → higher priority), and Earliest Deadline First (EDF), where the task with the closest deadline gets the highest priority dynamically. These algorithms are essential in embedded systems, avionics, and industrial control.

    实时系统要求严格的时间保证。两种常见的方法是:速率单调调度(RMS),它根据任务的周期分配静态优先级(周期越短优先级越高);以及最早截止时间优先(EDF),它动态地将最高优先级赋予截止时间最近的任务。这些算法在嵌入式系统、航空电子和工业控制中至关重要。


    10. Scheduling Algorithm Evaluation | 调度算法的评估

    We compare scheduling algorithms using several criteria: CPU utilisation (keeping the CPU busy), throughput (number of processes completed per time unit), turnaround time (time from submission to completion), waiting time (time spent in the ready queue), and response time (time from submission to the first response). Deterministic modelling, queueing models, and simulations help evaluate algorithms under different workloads.

    我们用若干标准来比较调度算法:CPU 利用率(保持 CPU 忙碌)、吞吐量(单位时间完成的进程数)、周转时间(从提交到完成的时间)、等待时间(在就绪队列里等待的时间)以及响应时间(从提交到首次响应的时间)。确定性建模、排队模型和仿真有助于在不同工作负载下评估算法。


    11. Implementation in Code: A Simple Round Robin Simulator | 代码实现:一个简单的轮转调度模拟器

    To solidify your understanding, consider a Python simulation of Round Robin. Represent each process as an object with attributes for arrival time, burst time, and remaining time. Use a queue to hold ready processes. The main loop increments time, enqueues newly arrived processes, and gives the current process a time slice. If the process completes, record its statistics; if not, re‑enqueue it. This hands‑on exercise reinforces the theoretical concepts and prepares you for the coding aspects of the A‑level exam.

    为了巩固理解,可以用 Python 编写一个轮转调度的模拟程序。将每个进程表示为一个对象,包含到达时间、执行时间和剩余时间等属性。使用一个队列来存放就绪进程。主循环递增时间、将新到达的进程入队,并给当前进程一个时间片。如果进程完成,记录其统计信息;否则重新入队。这个动手练习能够强化理论概念,并为 A‑level 考试中的编程部分做好准备。


    12. Common Pitfalls and Exam Tips | 常见误区与考试技巧

    Students often confuse waiting time with response time, or forget that the average turnaround time includes the entire execution period plus all waiting. When drawing Gantt charts, clearly label process IDs and time stamps. In SRID analyses, be careful to check at every arrival whether preemption should occur. Practice with varied quantum values in RR to see why 80% of CPU bursts should typically be shorter than the time quantum for optimal performance.

    学生常常混淆等待时间与响应时间,或者忘记平均周转时间包括整个执行周期加上所有等待时间。绘制甘特图时,要清楚地标注进程 ID 和时间戳。在分析 SRTF 时,要仔细在每个到达时刻检查是否应该发生抢占。多练习 RR 中不同时间片值的场景,以理解为什么通常 80% 的 CPU 执行时间应该短于时间片才能获得最佳性能。

    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Combined Operations on Data Structures in A-Level Programming | 数据结构组合操作在A-Level编程中的应用

    📚 Combined Operations on Data Structures in A-Level Programming | 数据结构组合操作在A-Level编程中的应用

    When tackling complex computational problems in Edexcel A-Level Programming, a single operation on a data structure rarely solves the task in isolation. Instead, exam questions increasingly focus on combining multiple operations—pushing onto a stack while checking for overflow, enqueuing and immediately checking the front element, or traversing a tree to collect data and then sorting the result. Understanding how these operations work together is essential for writing efficient pseudocode, interpreting trace tables, and designing robust algorithms under timed conditions.

    在Edexcel A-Level编程考试中,处理复杂计算问题时,单一数据结构操作很少能独立完成任务。考题越来越侧重于组合多种操作——在压入栈的同时检查是否溢出,入队后立即查看队首元素,或者遍历树来收集数据然后对结果进行排序。理解这些操作如何协同工作,对于在限时条件下编写高效伪代码、解读跟踪表以及设计稳健的算法至关重要。

    1. The Role of Operation Chains in Computational Thinking | 操作链在计算思维中的作用

    An operation chain links primitive data structure commands—such as push, pop, insert, delete, and peek—into a sequence that solves a sub-problem. In Edexcel’s Paper 2, you are often asked to complete or debug such chains. For example, reversing a string involves pushing all characters onto a stack, then popping them into a new string. That two-stage process combines push and pop in a purposeful order, illustrating how abstraction turns simple operations into a solution.

    操作链将基本的数据结构命令——如压入、弹出、插入、删除和查看——连接成一个解决子问题的序列。在Edexcel的Paper 2中,你经常需要补全或调试这样的链条。例如,反转一个字符串涉及将所有字符压入栈,然后弹出到新字符串中。这个两阶段过程按特定顺序组合了压入和弹出,展示了抽象如何将简单操作转化为解决方案。

    2. Stack Combinations: Push, Pop, and Peek in Sequence | 栈的组合:压入、弹出与查看的序列

    A stack’s LIFO behaviour makes it ideal for backtracking and syntax checking. Consider a balanced bracket validator: we iterate over a string, push opening brackets onto a stack, and when encountering a closing bracket, we first peek to check matching, then pop if valid. The combined use of push and conditional peek/pop ensures correctness. Pseudocode often tests isEmpty() before popping to avoid underflow, forcing you to chain a Boolean check with the removal operation.

    栈的后进先出特性使其非常适合回溯和语法检查。考虑一个平衡括号验证器:我们遍历字符串,将开括号压入栈,当遇到闭括号时,首先查看栈顶以检查匹配,如果有效则弹出。压入与条件查看/弹出的组合使用确保了正确性。伪代码通常在弹出前测试isEmpty()以避免下溢,这迫使你将布尔检查与删除操作链接起来。

    3. Queue Combinations: Enqueue, Dequeue, and Circular Logic | 队列的组合:入队、出队与循环逻辑

    Queues shine in scenarios like printer spooling or process scheduling. A combined operation pattern appears in circular queues: after advancing the rear pointer and inserting an element, we must immediately check if rear has caught up with front to detect a full condition. Similarly, priority queues require enqueuing with a priority value and then, during dequeue, searching for the highest priority element before removal. This merges enqueue, linear search, and shift-left operations.

    队列在打印后台处理或进程调度等场景中表现出色。循环队列中出现了一种组合操作模式:在移动尾指针并插入元素后,我们必须立即检查尾指针是否追上了头指针以检测队列满的条件。类似地,优先队列要求带着优先级值入队,然后在出队期间先搜索最高优先级元素再删除。这融合了入队、线性搜索和左移操作。

    4. Linked List Traversal Combined with Deletion and Insertion | 链表遍历结合删除与插入

    Many exam problems ask for removing a node with a specific value while preserving list order. You must traverse the list, maintain a ‘previous’ pointer, and when the target is found, adjust previous.next to current.next. This combines a while-loop traversal with pointer reassignment. A more advanced combination is inserting a node in a sorted linked list: traverse to find the correct position, then perform a standard insertion by updating two references.

    许多考题要求删除具有特定值的节点同时保持列表顺序。你必须遍历链表,维护一个“前驱”指针,当找到目标时,将前驱的next调整为当前节点的next。这结合了while循环遍历和指针重新赋值。更高级的组合是在有序链表中插入节点:遍历以找到正确位置,然后通过更新两个引用来执行标准插入。

    5. Binary Search Tree Operations: Search Followed by Insert or Delete | 二叉搜索树操作:搜索后插入或删除

    BST operations naturally combine comparison with recursive or iterative traversal. When inserting, you first search for the appropriate leaf position, then create the new node. Deletion is even more involved: search to locate the node, then handle three cases—leaf, one child, or two children. The two-child case requires finding the in-order successor (a search operation) before transplanting the value. These sequences test your ability to nest one operation inside another while managing tree pointers.

    BST操作自然地将比较与递归或迭代遍历结合起来。插入时,你首先搜索合适的叶节点位置,然后创建新节点。删除更为复杂:搜索以定位节点,然后处理三种情况——叶节点、单子节点或双子节点。双子节点情况需要先找到中序后继(一次搜索操作),再移植值。这些序列考验你在管理树指针的同时将一项操作嵌套在另一项操作中的能力。

    6. Combining Stack and Queue to Simulate a Deque | 组合栈与队列来模拟双端队列

    A deque supports insertions and deletions at both ends. One classic implementation uses two stacks or a queue plus a stack. For example, to add to the front, you might push onto a front-stack; to remove from the front, you pop from that same stack—provided it is not empty, else you transfer elements from the back queue. This strategy chains conditional checks with bulk move operations, a perfect exam question pattern.

    双端队列支持在两端进行插入和删除。一种经典的实现使用两个栈或一个队列加一个栈。例如,要添加至前端,你可以压入前端栈;要从前端删除,如果前端栈非空就直接弹出,否则需要将元素从后端队列批量转移过来。这种策略将条件检查与批量移动操作链接起来,是完美的考题模式。

    7. Table-Based Analysis of Combined Operations | 基于表格的组合操作分析

    Trace tables are a staple of Paper 2. When a question describes a sequence like: ‘push 5, push 3, pop, push 8, pop, pop,’ you need to show the stack state after each combined step. Below is a sample trace for a stack with maximum size 3, demonstrating overflow detection:

    跟踪表是Paper 2的重点内容。当题目描述一个顺序如:“push 5, push 3, pop, push 8, pop, pop”,你需要展示每一步组合操作后的栈状态。以下是一个最大容量为3的栈的示例跟踪,展示溢出检测:

    Step Operation Condition Check Stack Content (top -> bottom)
    1 push(5) not full [5]
    2 push(3) not full [3,5]
    3 pop() not empty [5]
    4 push(8) not full [8,5]
    5 push(2) not full [2,8,5]
    6 push(9) full -> overflow error [2,8,5]

    Notice how each row explicitly pairs the operation with a condition check, exactly as examiners expect in trace tables.

    注意每一行都明确将操作与条件检查配对,这正是考试评分者希望在跟踪表中看到的。

    8. Algorithmic Fusion: Sorting Before Searching | 算法融合:搜索前先排序

    Although binary search requires a sorted array, the sorting operation itself is often omitted from the high-level description but must be accounted for in complexity analysis. When a question asks: ‘describe an algorithm to find the median,’ you combine a sort (like quicksort) with an index access (middle element). The overall time complexity becomes O(n log n) + O(1), dominated by the sort. This demonstrates how operation combination affects efficiency decisions.

    尽管二分搜索要求数组有序,排序操作本身通常在高层次描述中被省略,但在复杂度分析中必须加以考虑。当题目要求“描述寻找中位数的算法”时,你将排序(如快速排序)与索引访问(中间元素)结合起来。总时间复杂度变为O(n log n) + O(1),由排序主导。这表明操作组合如何影响效率决策。

    9. Graph Traversal with Adjacency List and Stack/Queue | 图的遍历与邻接表及栈/队列的组合

    Depth-first search uses a stack (explicitly or via recursion), while breadth-first search uses a queue. In both cases, you combine graph representation operations—fetching neighbours from an adjacency list—with push/enqueue and pop/dequeue. For example, in BFS, you dequeue a vertex, iterate through its neighbours, and enqueue any unvisited ones. That tight loop of dequeue-check-enqueue forms the core of many shortest-path questions.

    深度优先搜索使用栈(显式或通过递归),而广度优先搜索使用队列。在这两种情况下,你将图的表示操作——从邻接表中获取邻居——与压入/入队和弹出/出队结合起来。例如,在BFS中,你出队一个顶点,遍历其邻居,并将未访问的入队。这种出队-检查-入队的紧密循环构成了许多最短路径问题的核心。

    10. Recursive Combinations: Base Case and Recursive Call on Trees | 递归组合:树的基案与递归调用

    Recursion naturally combines operations: a tree size function returns 0 for a null node, else 1 + left subtree size + right subtree size. Here, the operations are the arithmetic sum and the two recursive traversals. Similarly, calculating the height requires combining 1 + max(leftHeight, rightHeight), blending max function with recursion. These examples test your ability to track multiple pending operations in a call stack.

    递归自然地组合操作:一个计算树大小的函数对空节点返回0,否则返回1 + 左子树大小 + 右子树大小。这里的操作是算术求和以及两次递归遍历。类似地,计算高度需要组合1 + max(左高度, 右高度),将max函数与递归融合。这些例子考验你在调用栈中追踪多个待处理操作的能力。

    11. Debugging and Trace Table Practice for Combined Operations | 组合操作的调试与跟踪表练习

    A common exam pitfall is forgetting to check boundary conditions during operation chains. For instance, when implementing a queue using two stacks, popping from an empty stack while the other contains elements requires a ‘shift’ step. If your pseudocode skips the isEmpty() check before shifting, the entire sequence fails. Practice drawing trace tables for sequences that mix push, pop, enqueue, and dequeue to internalise the state transitions.

    常见的考试陷阱是在操作链中忘记检查边界条件。例如,当用两个栈实现队列时,从一个空栈弹出而另一个栈包含元素时,需要一个“转移”步骤。如果你的伪代码在转移前跳过了isEmpty()检查,整个序列就会失败。通过练习绘制混合了压入、弹出、入队和出队的序列的跟踪表,将状态转换内化于心。

    12. Exam Strategy: Breaking Down Multi-Operation Questions | 考试策略:分解多操作题目

    When faced with a 6-mark algorithm design question, identify the primary data structure first. Then list the essential sub-operations: initialisation, a loop with access/modification, and a final retrieval. Write pseudocode step by step, adding pre- and post-condition comments. For example, ‘Find the second largest element in a BST’ requires: 1) reverse in-order traversal (right-root-left), 2) counting nodes visited, 3) stopping after two. Each step is a combined use of traversal and counter logic.

    面对6分的算法设计题时,首先确定主要数据结构。然后列出必要的子操作:初始化、带有访问/修改的循环以及最终检索。逐步编写伪代码,添加前置和后置条件注释。例如,“在BST中查找第二大元素”需要:1) 逆序中序遍历(右-根-左),2) 对访问的节点进行计数,3) 访问两个后停止。每一步都是遍历与计数器逻辑的组合使用。

    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming (OOP) for Edexcel A-Level Computer Science | 艾德思 A-Level 计算机科学中的面向对象编程

    📚 Object-Oriented Programming (OOP) for Edexcel A-Level Computer Science | 艾德思 A-Level 计算机科学中的面向对象编程

    Object-oriented programming (OOP) is a fundamental paradigm in modern software development, and it is a core topic in the Edexcel A-Level Computer Science specification. Understanding OOP not only helps you write more organised and reusable code but also equips you with the skills needed to tackle larger programming projects and exam questions. This guide explores key OOP concepts using Python, the language most commonly used in the course, with clear explanations and practical examples.

    面向对象编程是现代软件开发中的基本范式,也是艾德思 A-Level 计算机科学大纲中的核心主题。理解面向对象编程不仅能帮助你编写更有条理、可复用的代码,还能让你掌握应对大型编程项目和考试题目所需的技能。本指南使用课程中最常用的 Python 语言,通过清晰的解释和实际示例,深入探讨关键的 OOP 概念。


    1. What is Object-Oriented Programming? | 什么是面向对象编程?

    Object-oriented programming (OOP) organises software design around objects rather than functions and logic. An object is a self-contained entity that contains both data in the form of attributes (also called fields or properties) and procedures in the form of methods. This paradigm models real-world entities, making code easier to understand, maintain, and extend. In Edexcel A-Level, you are expected to recognise the differences between procedural and object-oriented approaches.

    面向对象编程(OOP)围绕对象而非函数和逻辑来组织软件设计。对象是一个自包含的实体,其中既包含以属性(也称为字段或属性)形式存在的数据,也包含以方法形式存在的程序。这种范式对现实世界中的实体进行建模,使代码更易于理解、维护和扩展。在艾德思 A-Level 课程中,你需要认识到过程式方法和面向对象方法之间的区别。


    2. Classes and Objects | 类与对象

    A class is a blueprint for creating objects. It defines a set of attributes and methods that the objects created from it will have. An object is an instance of a class. For example, a class Car might define attributes such as colour and speed, and methods like accelerate(). Creating an object my_car = Car('red') allocates memory for that specific instance. In Python, classes are defined using the class keyword.

    类是创建对象的蓝图。它定义了一组属性和方法,由该类创建的对象都将拥有这些属性和方法。对象是类的一个实例。例如,一个 Car 类可以定义 colourspeed 等属性,以及 accelerate() 等方法。创建对象 my_car = Car('red') 会为该特定实例分配内存。在 Python 中,类使用 class 关键字进行定义。

    class Car:
        def __init__(self, colour):
            self.colour = colour
            self.speed = 0
    
        def accelerate(self, increment):
            self.speed += increment
    

    3. Attributes and Methods | 属性与方法

    Attributes store data about an object. They can be instance variables, which are unique to each object, or class variables, which are shared across all instances. Methods define the behaviour of an object. In Python, the first parameter of an instance method is always self, which refers to the current object. Accessor methods (getters) retrieve attribute values, while mutator methods (setters) modify them, supporting the principle of encapsulation.

    属性存储关于对象的数据。它们可以是实例变量(每个对象独有),也可以是类变量(在所有实例间共享)。方法定义了对象的行为。在 Python 中,实例方法的第一个参数始终是 self,它指向当前对象。访问器方法(getter)用于获取属性值,而修改器方法(setter)用于修改属性值,从而支持封装原则。


    4. Constructors and the __init__ Method | 构造方法与 __init__ 方法

    A constructor is a special method that is automatically called when an object is instantiated. In Python, the __init__ method serves as the constructor. It initialises the object’s attributes and can take parameters to set initial states. For example, def __init__(self, make, model): allows you to create an object with those values. The Edexcel specification often requires you to write or interpret constructor methods correctly.

    构造方法是一种特殊方法,在对象实例化时自动调用。在 Python 中,__init__ 方法充当构造方法的角色。它初始化对象的属性,并可以接收参数来设置初始状态。例如,def __init__(self, make, model): 允许你使用这些数值创建对象。艾德思大纲常要求你正确编写或解释构造方法。


    5. Encapsulation and Access Modifiers | 封装与访问修饰符

    Encapsulation bundles data and methods that operate on that data within one unit, and it restricts direct access to some of an object’s components. This is achieved through naming conventions in Python: a single underscore prefix (e.g., _attribute) indicates a protected member, while a double underscore (e.g., __attribute) triggers name mangling to make it harder to access from outside the class. Although Python does not enforce strict access control like Java or C++, these conventions are important for writing robust and maintainable code.

    封装将数据和操作这些数据的方法捆绑在一个单元内,并限制对对象某些组件的直接访问。在 Python 中,这通过命名约定来实现:单下划线前缀(例如 _attribute)表示受保护的成员,而双下划线前缀(例如 __attribute)会触发名称改写,使得从类外部访问变得更加困难。虽然 Python 不像 Java 或 C++ 那样强制执行严格的访问控制,但这些约定对于编写健壮且易于维护的代码至关重要。


    6. Inheritance | 继承

    Inheritance allows a class (subclass or child class) to inherit attributes and methods from another class (superclass or parent class). 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 methods from the parent and can also introduce new attributes. For Edexcel A-Level, you need to be able to design and analyse class hierarchies using inheritance.

    继承允许一个类(子类或派生类)从另一个类(超类或父类)继承属性和方法。这促进了代码复用,并建立了层次化关系。在 Python 中,你在括号中指定父类:class ElectricCar(Car):。子类可以重写父类的方法,还可以引入新的属性。对于艾德思 A-Level,你需要能够使用继承设计并分析类的层次结构。


    7. Polymorphism | 多态

    Polymorphism means ‘many forms’. In OOP, it allows objects of different classes to respond to the same method call in their own way. This is commonly achieved through method overriding. For instance, a Shape superclass might declare a method area(), and subclasses Circle and Rectangle implement it differently. When you call shape.area(), the correct version is executed based on the object’s actual class. Polymorphism is a core concept examined in A-Level questions.

    多态意味着“多种形态”。在 OOP 中,它允许不同类的对象以各自的方式响应相同的方法调用。这通常通过方法重写来实现。例如,Shape 超类可以声明一个 area() 方法,而 CircleRectangle 子类以不同的方式实现该方法。当你调用 shape.area() 时,会根据对象的实际类执行正确的版本。多态是 A-Level 试题中考查的核心概念。


    8. Abstract Classes and Interfaces | 抽象类与接口

    An abstract class is a class that cannot be instantiated and is designed to be subclassed. It may contain abstract methods—methods without implementation—that subclasses must override. In Python, the abc module provides the ABC base class and the @abstractmethod decorator. Interfaces, while not a built-in feature in Python as in Java, are conceptually similar: they define a set of methods that a class must implement. Understanding these helps you design flexible and extensible systems.

    抽象类是无法实例化且设计用于派生子类的类。它可以包含抽象方法——即没有实现的方法——子类必须重写这些方法。在 Python 中,abc 模块提供了 ABC 基类和 @abstractmethod 装饰器。接口虽然在 Python 中不像 Java 那样是内置特性,但概念上相似:它们定义了一组类必须实现的方法。理解这些概念有助于你设计灵活且可扩展的系统。


    9. Practical Example: A Library Management System | 实际示例:图书馆管理系统

    Let’s consolidate these concepts with a simple library system. Define a base class LibraryItem with attributes title, item_id and an abstract method get_loan_period(). Subclasses Book and DVD inherit from LibraryItem and implement the method. A Member class can contain a list of borrowed items. This demonstrates inheritance, polymorphism, and encapsulation. Write and trace such code to prepare for practical programming tasks.

    让我们通过一个简单的图书馆系统来整合这些概念。定义一个基类 LibraryItem,包含属性 titleitem_id 以及抽象方法 get_loan_period()。子类 BookDVD 继承 LibraryItem 并实现该方法。一个 Member 类可以包含一个借阅物品列表。这展示了继承、多态和封装。编写并追踪此类代码,为实际编程任务做好准备。

    from abc import ABC, abstractmethod
    
    class LibraryItem(ABC):
        def __init__(self, title, item_id):
            self.title = title
            self.item_id = item_id
    
        @abstractmethod
        def get_loan_period(self):
            pass
    
    class Book(LibraryItem):
        def get_loan_period(self):
            return 21  # days
    
    class DVD(LibraryItem):
        def get_loan_period(self):
            return 7
    

    10. Benefits of OOP | 面向对象编程的优势

    OOP brings several advantages that make it suitable for large-scale software development: modularity (objects are self-contained), reusability (inheritance allows code reuse), flexibility (polymorphism enables dynamic behaviour), and maintainability (encapsulation hides complexity). These benefits directly align with the Edexcel A-Level assessment objectives, where you may be asked to justify the use of OOP over procedural programming.

    OOP 带来了若干优势,使其适用于大规模软件开发:模块化(对象自包含)、可复用性(继承允许代码复用)、灵活性(多态支持动态行为)以及可维护性(封装隐藏了复杂性)。这些优点与艾德思 A-Level 的评估目标直接吻合,考试中可能会要求你说明使用 OOP 而非过程式编程的理由。


    11. OOP vs Procedural Programming | 面向对象编程与过程式编程

    Procedural programming structures code as a sequence of instructions operating on shared data, often using functions. OOP bundles data and functions into objects. Key differences include data hiding (encapsulation in OOP vs global variables in procedural), ease of modelling real-world problems, and scalability. Edexcel questions sometimes present pseudocode and ask you to convert a procedural solution into an object-oriented design, or to compare the two approaches.

    过程式编程将代码结构化为一系列对共享数据进行操作的指令,常使用函数。OOP 将数据和函数捆绑到对象中。关键区别包括数据隐藏(OOP 中的封装与过程式中的全局变量)、对真实世界问题建模的难易程度以及可扩展性。艾德思的题目有时会提供伪代码,要求你将过程式解决方案转换为面向对象的设计,或者比较这两种方法。


    12. Exam Tips for Edexcel A-Level OOP Questions | 艾德思 A-Level 面向对象编程考题技巧

    When tackling OOP questions, always read the scenario carefully and identify the candidate classes, their attributes, and their relationships (‘is-a’ for inheritance, ‘has-a’ for composition). Use standard UML class diagrams where required. In coding tasks, remember to include a constructor, use correct self syntax, and demonstrate inheritance and polymorphism explicitly. Practise writing both short code snippets and longer structured programs under timed conditions to build confidence.

    在处理面向对象编程题目时,务必仔细阅读场景,并确定候选类、它们的属性以及关系(“是-一种”对应继承,“有-一个”对应组合)。在需要时使用标准的 UML 类图。在编程任务中,记住包含构造方法、使用正确的 self 语法,并明确地展示继承和多态。在计时条件下练习编写简短的代码片段和较长的结构化程序,以建立信心。


    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Mastering Operator Precedence and Combined Operations | 掌握运算符优先级与组合运算

    📚 Mastering Operator Precedence and Combined Operations | 掌握运算符优先级与组合运算

    In A-Level Computer Science, understanding how operators interact within expressions is foundational for writing correct and efficient code. Operator precedence determines the order in which different operations are evaluated when they appear together, and mastering it helps programmers avoid subtle bugs. This article breaks down the rules for arithmetic, relational, logical, bitwise, and assignment operators, explaining both precedence and associativity with clear examples. We will explore how combined operations are handled in many programming languages, with a focus on the concepts required by the Edexcel specification.

    在A-Level计算机科学中,理解运算符在表达式中的相互作用是编写正确高效代码的基础。运算符优先级决定了不同运算同时出现时的执行顺序,掌握它有助于程序员避免难以察觉的错误。本文将分解算术、关系、逻辑、位运算和赋值运算符的规则,通过清晰的例子解释优先级和结合性。我们将探讨许多编程语言中组合运算的处理方式,重点围绕Edexcel考纲要求的概念。


    1. The Role of Operators in Programming | 运算符在编程中的作用

    Operators are symbols that tell the compiler or interpreter to perform specific mathematical, relational, or logical manipulations. They are the building blocks of expressions, allowing us to compute values, compare data, and control program flow. Without a well-defined order of evaluation, an expression like a + b * c would be ambiguous. Precedence rules resolve this by giving multiplication a higher priority than addition, so the multiplication happens first.

    运算符是告诉编译器或解释器执行特定数学、关系或逻辑操作的符号。它们是表达式的基本构件,使我们能够计算值、比较数据和控制程序流程。如果没有明确的求值顺序,像 a + b * c 这样的表达式就会产生歧义。优先级规则通过赋予乘法高于加法的优先级来解决这个问题,因此乘法会先进行。


    2. Arithmetic Operator Precedence | 算术运算符优先级

    Arithmetic operators follow a standard hierarchy familiar from mathematics: parentheses first, then exponentiation (if supported), followed by multiplication, division, and modulus, and finally addition and subtraction. In many languages, multiplication and division share the same precedence and are evaluated left to right. For example, 10 – 4 / 2 yields 8 because division occurs before subtraction.

    算术运算符遵循数学中熟悉的标准层次:先括号,然后是指数(如果支持),接着是乘法、除法和取模,最后是加法和减法。在许多语言中,乘法和除法具有相同的优先级,并按从左到右的顺序求值。例如,10 – 4 / 2 的结果是 8,因为除法在减法之前进行。

    Precedence Operator Description
    Highest ( ) Parentheses
    ** or ^ (language dependent) Exponentiation
    * / % Multiplication, division, modulus
    Lowest + – Addition, subtraction

    3. Relational and Comparison Operators | 关系与比较运算符

    Relational operators compare two values and return a Boolean result. They include less than (<), greater than (>), less than or equal to (≤), greater than or equal to (≥), equal to (= or ==), and not equal to (≠ or !=). These operators have lower precedence than arithmetic operators but higher than logical operators. For instance, in the expression a + b < c * d, the additions and multiplications are performed before the comparison.

    关系运算符比较两个值并返回布尔结果。它们包括小于 (<)、大于 (>)、小于等于 (≤)、大于等于 (≥)、等于 (= 或 ==) 和不等于 (≠ 或 !=)。这些运算符的优先级低于算术运算符,但高于逻辑运算符。例如,在表达式 a + b < c * d 中,加法和乘法会在比较之前执行。


    4. Logical Operators: AND, OR, NOT | 逻辑运算符:与、或、非

    Logical operators combine Boolean values and are essential in decision-making structures. Typical precedence order is NOT first, then AND, and finally OR. This means NOT p AND q is interpreted as (NOT p) AND q, not NOT (p AND q). Many languages also feature short-circuit evaluation, where the second operand of AND or OR is only evaluated if necessary. Understanding this can prevent runtime errors, such as checking for null before accessing an object’s property.

    逻辑运算符组合布尔值,在决策结构中至关重要。典型的优先级顺序是 NOT 最高,然后是 AND,最后是 OR。这意味着 NOT p AND q 被解释为 (NOT p) AND q,而不是 NOT (p AND q)。许多语言还具有短路求值特性,即 AND 或 OR 的第二个操作数仅在必要时才求值。理解这一点可以防止运行时错误,例如在访问对象属性前检查是否为 null。


    5. Bitwise Operators in Combined Expressions | 组合表达式中的位运算符

    Bitwise operators act on the binary representations of integers. They include AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). Their precedence sits between relational and logical operators in many languages. For example, a & b == c may not behave as expected because equality (==) has higher precedence than bitwise AND. To avoid confusion, use parentheses to make the intent clear.

    位运算符作用于整数的二进制表示。它们包括按位与 (&)、按位或 (|)、按位异或 (^)、按位非 (~)、左移 (<<) 和右移 (>>)。在许多语言中,其优先级介于关系运算符和逻辑运算符之间。例如,a & b == c 可能不会按预期执行,因为等号 (==) 的优先级高于按位与。为避免混淆,应使用括号明确意图。


    6. Assignment Operators and Their Low Precedence | 赋值运算符及其低优先级

    Assignment operators (=, +=, -=, *=, etc.) have very low precedence, typically lower than almost all other operators. This allows expressions on the right-hand side to be fully evaluated before the assignment takes place. For instance, x = a + b * c is evaluated as x = (a + (b * c)). Chained assignments like x = y = z = 0 work because assignment is right-to-left associative, assigning zero to z first, then to y, then to x.

    赋值运算符(=, +=, -=, *= 等)的优先级非常低,通常低于几乎所有其他运算符。这使得右侧的表达式在赋值发生之前被完整求值。例如,x = a + b * c 的计算过程是 x = (a + (b * c))。像 x = y = z = 0 这样的链式赋值之所以有效,是因为赋值是右结合性,先将零赋给 z,再赋给 y,最后赋给 x。


    7. Operator Associativity: Left-to-Right vs Right-to-Left | 运算符结合性:左结合与右结合

    When two operators have the same precedence, associativity determines the direction of evaluation. Most arithmetic operators are left-associative, so 10 – 3 – 2 is treated as (10 – 3) – 2, yielding 5. In contrast, assignment and exponentiation operators are usually right-associative. For example, a = b = 5 works because assignment associates right-to-left. Understanding associativity prevents misinterpretation of expressions with repeated operators.

    当两个运算符具有相同的优先级时,结合性决定了求值的方向。大多数算术运算符是左结合的,因此 10 – 3 – 2 被视为 (10 – 3) – 2,结果为 5。相反,赋值和指数运算符通常是右结合的。例如,a = b = 5 之所以有效,是因为赋值是从右向左结合的。理解结合性可以防止对带有重复运算符的表达式的误读。


    8. The Power of Parentheses for Clarity | 括号的力量:提升清晰度

    Even when precedence rules are well known, inserting parentheses can dramatically improve code readability and prevent logical errors. They override all default precedence and associativity, forcing subexpressions to be evaluated first. In complex conditions like (age >= 18 && hasID) || accompaniedByAdult, parentheses group the AND condition together, making the intended logic explicit. Exam questions often require you to rewrite an expression with added parentheses to demonstrate your understanding of evaluation order.

    即使优先级规则众所周知,插入括号也可以显著提高代码的可读性并防止逻辑错误。它们覆盖所有默认的优先级和结合性,强制子表达式优先求值。在类似 (age >= 18 && hasID) || accompaniedByAdult 的复杂条件中,括号将 AND 条件分组在一起,使预期的逻辑变得明确。考试题经常要求你通过添加括号来重写表达式,以展示你对求值顺序的理解。


    9. Data Type Conversion in Mixed Expressions | 混合表达式中的数据类型转换

    When an expression involves operands of different types, implicit type conversion (coercion) may occur according to language rules. For example, in many languages, an integer added to a floating-point number results in a floating-point value. Precedence remains unchanged, but the type of intermediate results can affect final outcomes. Be aware that division of two integers may perform integer division, discarding the remainder unless explicitly cast.

    当表达式中包含不同类型的操作数时,可能会根据语言规则发生隐式类型转换(强制转换)。例如,在许多语言中,整数与浮点数相加会得到浮点数值。优先级保持不变,但中间结果的类型可能会影响最终结果。请注意,两个整数相除可能会执行整数除法,丢弃余数,除非进行显式转换。


    10. Real-World Pitfalls and Debugging Tips | 真实世界的陷阱与调试技巧

    A common mistake is misjudging the precedence of logical NOT with respect to comparison operators. The expression ! x > 5 may be parsed as (!x) > 5 rather than the intended !(x > 5), leading to unexpected behavior. To debug such issues, break down compound expressions into multiple simpler statements, or use an IDE’s parentheses-highlighting feature. Tracing the order of evaluation with a precedence table can save hours of frustration.

    一个常见的错误是误判逻辑非相对于比较运算符的优先级。表达式 ! x > 5 可能被解析为 (!x) > 5,而不是预期的 !(x > 5),从而导致意外行为。要调试此类问题,可以将复合表达式分解为多个更简单的语句,或使用 IDE 的括号高亮功能。使用优先级表追踪求值顺序可以节省大量懊恼时间。


    11. Exam-Focused Advice for Edexcel A-Level | Edexcel A-Level 考试重点建议

    Edexcel questions frequently ask you to evaluate expressions step by step, showing the order in which operators are applied. Be prepared to construct truth tables that involve combined logical and comparison operations. You may also be asked to identify errors in given code snippets where incorrect precedence leads to logic flaws. Practice rewriting expressions using parentheses to alter the default order, and always state the precedence rules you are applying.

    Edexcel 的试题经常要求你逐步计算表达式,并显示运算符的执行顺序。做好构建真值表的准备,这些真值表涉及组合的逻辑和比较运算。你还可能被要求识别给定代码片段中的错误,这些错误是由于不正确的优先级而导致逻辑缺陷。练习使用括号重写表达式以改变默认顺序,并始终说明你所应用的优先级规则。


    12. Summary and Key Takeaways | 总结与要点

    Operator precedence and associativity form a contract that all programmers rely on, yet they can be easily forgotten. The key is to remember the general hierarchy: parentheses, unary, arithmetic, relational, logical, assignment. When in doubt, use parentheses—they cost nothing and make your intentions crystal clear. Regular practice with combined operations will build the fluency needed for both exams and real-world coding, ensuring you write robust, error-free programs.

    运算符优先级和结合性构成了所有程序员所依赖的约定,但它们很容易被遗忘。关键是要记住大致的层次结构:括号、一元运算符、算术、关系、逻辑、赋值。当有疑问时,使用括号——它们没有任何成本,却能让你的意图异常清晰。定期练习组合运算将培养考试和实际编码所需的熟练度,确保你编写出健壮、无错误的程序。


    Published by TutorHao | Computer Science Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming Fundamentals | 面向对象编程基础

    📚 Object-Oriented Programming Fundamentals | 面向对象编程基础

    Object-oriented programming (OOP) revolutionised software development by organising code around data rather than logic. In this article, we explore the core principles that underpin modern high-level languages such as Java, Python, and C#, aligning with the Edexcel A-Level Computer Science specification. You will learn how classes and objects model real-world entities, and how encapsulation, inheritance, and polymorphism promote maintainable and reusable code.

    面向对象编程(OOP)通过围绕数据而非逻辑来组织代码,彻底改变了软件开发。本文将探索支撑现代高级语言(如Java、Python和C#)的核心原则,与Edexcel A-Level计算机科学课程大纲保持一致。你将学习类和对象如何对现实世界实体进行建模,以及封装、继承和多态如何促进可维护、可复用的代码。


    1. What Is Object-Oriented Programming? | 什么是面向对象编程?

    OOP is a programming paradigm that uses ‘objects’ – self-contained units combining data and behaviour – to design applications. Unlike procedural programming, which focuses on a sequence of instructions, OOP structures software as a collection of interacting objects. This approach mirrors how we perceive the real world, making it easier to manage complexity.

    面向对象编程是一种使用“对象”(结合了数据与行为的独立单元)来设计应用程序的编程范式。与关注指令序列的过程式编程不同,OOP 将软件构建为相互交互的对象的集合。这种方法反映我们感知现实世界的方式,从而更容易管理复杂性。


    2. Classes and Objects | 类与对象

    A class is a blueprint or template that defines the attributes and behaviours common to a group of objects. For example, a Car class might define properties such as colour, make, and currentSpeed, as well as methods like accelerate() and brake(). An object is a specific instance of a class, created from that blueprint. In code, you might write:

    类是一个蓝图或模板,定义了一组对象共有的属性和行为。例如,一个Car类可能定义颜色、品牌和当前速度等属性,以及 accelerate() 和 brake() 等方法。对象是该类的一个具体实例,根据该蓝图创建。在代码中,你可能会写:

    Car myCar = new Car(‘Red’, ‘Toyota’);

    Here, myCar is an object of type Car. The class defines the structure, while objects hold actual values and can invoke methods.

    这里,myCar 是一个类型为 Car 的对象。类定义了结构,而对象保存实际值并可调用方法。


    3. Attributes and Methods | 属性与方法

    Attributes (also called fields or member variables) represent the state of an object. They are typically declared as variables inside the class. Methods define the behaviour of an object – the operations it can perform. A method can access and modify the object’s attributes, and may return a result. For instance, a BankAccount class might have an attribute balance and methods deposit(amount) and withdraw(amount).

    属性(也称为字段或成员变量)表示对象的状态。它们通常在类内部声明为变量。方法定义了对象的行为——它能够执行的操作。方法可以访问和修改对象的属性,并可能返回一个结果。例如,一个BankAccount类可能有一个属性balance,以及deposit(amount)withdraw(amount)方法。


    4. Encapsulation | 封装

    Encapsulation is the practice of hiding the internal details of an object and restricting direct access to some of its components. This is usually achieved by making attributes private and providing public getter and setter methods to interact with them. Encapsulation protects data from unintended modification and decouples the implementation from the interface. For example, a Temperature class could store Celsius internally but provide getFahrenheit() and setFahrenheit() methods, converting as needed.

    封装是将对象的内部细节隐藏起来,并限制对其某些组件的直接访问的做法。这通常通过将属性设为私有,并提供公共的 getter 和 setter 方法来与它们交互来实现。封装保护数据免受意外修改,并将实现与接口解耦。例如,Temperature类可以在内部存储摄氏温度,但提供 getFahrenheit() 和 setFahrenheit() 方法,根据需要进行转换。


    5. Access Modifiers | 访问修饰符

    Access modifiers control the visibility of class members. The most common are:

    访问修饰符控制类成员的可见性。最常见的有:

    • public – accessible from any other class. / 可从任何其他类访问。
    • private – accessible only within the same class. / 仅可在同一类中访问。
    • protected – accessible within the same package and by subclasses. / 可在同一包内及由子类访问。

    In A-Level contexts, understanding these modifiers is essential for implementing encapsulation and designing class hierarchies. Using private for attributes and public for methods is a standard convention.

    在A-Level情境中,理解这些修饰符对于实现封装和设计类层次结构至关重要。对属性使用private,对方法使用public是一种标准惯例。


    6. Constructors | 构造函数

    A constructor is a special method invoked when an object is instantiated. It typically initialises the object’s attributes and performs any setup required. In many languages, the constructor has the same name as the class and no return type. You can overload constructors to provide multiple ways of creating an object. Example: a Student class might have a default constructor and a parameterised constructor Student(String name, int id).

    构造函数是在对象实例化时调用的特殊方法。它通常初始化对象的属性并执行所需的任何设置。在许多语言中,构造函数与类同名且没有返回类型。你可以重载构造函数以提供多种创建对象的方式。例如:Student类可能有一个默认构造函数和一个带参数的构造函数 Student(String name, int id)


    7. Inheritance | 继承

    Inheritance allows a new class (subclass) to adopt the attributes and methods of an existing class (superclass). This promotes code reuse and establishes a natural hierarchical relationship. For instance, a Dog class can inherit from an Animal class, gaining properties like age and methods like eat(), while adding its own specialised behaviours such as wagTail(). The keyword extends (in Java) or : (in C#) is used to denote inheritance.

    继承允许新类(子类)采用现有类(超类)的属性和方法。这促进了代码复用,并建立了自然的层次关系。例如,Dog类可以继承自Animal类,获得如age属性和eat()方法,同时添加自己的特殊行为,如wagTail()。关键字extends(在Java中)或:(在C#中)用于表示继承。


    8. Polymorphism | 多态

    Polymorphism means ‘many forms’ and allows objects of different classes to be treated as objects of a common superclass. The most common type is method overriding, where a subclass provides a specific implementation of a method already defined in its superclass. A reference variable of the superclass type can point to a subclass object, and the correct overridden method is called at runtime (dynamic binding). For example:

    多态意味着“多种形态”,允许将不同类的对象视为共同超类的对象。最常见的类型是方法重写,即子类为其超类中已定义的方法提供具体实现。超类类型的引用变量可以指向子类对象,并且在运行时(动态绑定)调用正确的重写方法。例如:

    Animal a = new Dog(); a.speak();

    If speak() is overridden in Dog, the Dog’s version executes, not Animal’s.

    如果 speak() 在 Dog 中被重写,则执行 Dog 的版本,而不是 Animal 的。


    9. Overriding vs Overloading | 重写与重载

    A-Level specifications often require distinguishing between these two concepts. Overriding occurs when a subclass redefines a method with the same signature (name and parameter list) as in its superclass. It supports runtime polymorphism. Overloading happens when two or more methods in the same class share the same name but have different parameter lists (different number or types of parameters). Overloading is an example of compile-time polymorphism. In short: overriding = same signature, different class; overloading = same name, different parameters, same class.

    A-Level大纲通常要求区分这两个概念。重写发生在子类重新定义与其超类中具有相同签名(名称和参数列表)的方法时。它支持运行时多态。重载发生在同一类中的两个或多个方法共享相同名称但具有不同参数列表(不同数量或类型的参数)时。重载是编译时多态的一个例子。简而言之:重写 = 相同签名,不同类;重载 = 相同名称,不同参数,同一类。


    10. Abstraction | 抽象

    Abstraction focuses on exposing only the essential details while hiding the complex implementation. Abstract classes and interfaces are key tools. An abstract class cannot be instantiated directly and may contain abstract methods (methods without a body) that subclasses must implement. An interface defines a contract of methods that implementing classes must fulfil. For example, an abstract class Shape may declare an abstract method calculateArea(), leaving subclasses like Circle and Rectangle to provide concrete formulas.

    抽象专注于仅暴露关键细节而隐藏复杂实现。抽象类和接口是关键工具。抽象类不能直接实例化,并且可以包含抽象方法(没有方法体的方法),子类必须实现这些方法。接口定义了实现类必须履行的契约方法。例如,抽象类Shape可以声明一个抽象方法calculateArea(),留给CircleRectangle等子类提供具体公式。


    11. Association, Aggregation, and Composition | 关联、聚合与组合

    These terms describe relationships between classes beyond inheritance. Association is a generic ‘uses-a’ relationship, where one object interacts with another. Aggregation is a ‘has-a’ relationship where a whole is made up of parts, but the parts can exist independently (e.g., a Department has Employees). Composition is a stronger ‘has-a’ relationship where the parts cannot exist without the whole (e.g., a House is composed of Rooms; if the House is destroyed, the Rooms cease to exist). In UML, an empty diamond represents aggregation, and a filled diamond composition.

    这些术语描述了类之间的除了继承之外的关系。关联是一种通用的“使用”关系,一个对象与另一个对象交互。聚合是一种“拥有”关系,整体由部分组成,但部分可以独立存在(例如,Department 拥有 Employees)。组合是一种更强的“拥有”关系,部分不能独立于整体而存在(例如,House 由 Rooms 组成;如果 House 被销毁,Rooms 也不复存在)。在 UML 中,空心菱形表示聚合,实心菱形表示组合。


    12. Benefits and Real-World Relevance of OOP | 面向对象编程的优势与现实关联

    OOP offers modularity (code is organised into discrete classes), reusability (inheritance and libraries), scalability, and security (encapsulation). These benefits are why languages like Python, Java, and C++ dominate in industry. In your A-Level coursework, applying OOP principles will improve code design and help you achieve higher marks in the programming project. Understanding these fundamentals not only prepares you for the exam but also for university-level computer science and professional software development.

    OOP 提供了模块化(代码被组织为离散的类)、可复用性(继承和库)、可扩展性和安全性(封装)。这些优势正是 Python、Java 和 C++ 等在工业界占据主导地位的原因。在你的 A-Level 课程作业中,应用面向对象原则将改善代码设计,并帮助你在编程项目中取得更高分数。理解这些基础知识不仅为考试做准备,也为大学阶段的计算机科学及专业软件开发做好准备。


    Published by TutorHao | Computer Science Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)