Mastering Object-Oriented Programming | 掌握面向对象编程

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

Object-oriented programming (OOP) is a cornerstone of modern software development and a critical topic in the Edexcel A-Level Computer Science specification. Whether you are designing a small application or a large-scale system, OOP gives you tools to organise code logically, promote reuse, and manage complexity. This revision guide covers every essential OOP concept, from classes and objects to advanced design principles, using clear explanations and practical Python examples that align with the Pearson Edexcel syllabus.

面向对象编程(OOP)是现代软件开发的基石,也是 Edexcel A-Level 计算机科学课程中的关键主题。无论你是在设计小型应用还是大型系统,OOP 都能提供逻辑组织代码、促进重用和管理复杂性的工具。本复习指南涵盖了从类与对象到高级设计原则的每个核心 OOP 概念,并使用与 Pearson Edexcel 教学大纲一致的清晰解释和实用 Python 示例。


1. Introduction to Programming Paradigms | 编程范式简介

Programming paradigms are fundamental styles that shape how we think about code structure and problem solving. The two most prominent paradigms are procedural programming and object-oriented programming. Procedural programming sequences instructions and commonly uses functions to operate on separate data. Object-oriented programming, by contrast, bundles related data and behaviour into objects. This shift makes it easier to model real-world entities and build maintainable, modular software.

编程范式是塑造我们如何思考代码结构和问题解决的基本风格。最突出的两种范式是过程式编程和面向对象编程。过程式编程排序指令并通常使用函数对分离的数据进行操作。相比之下,面向对象编程将相关的数据和行为打包成对象。这种转变使得对现实世界实体进行建模以及构建可维护、模块化的软件变得更加容易。

The Edexcel A-Level specification expects you to appreciate the strengths of OOP, such as encapsulation, inheritance, and polymorphism. Understanding why these features matter lays the foundation for tackling larger programming projects and exam questions that ask you to compare paradigms or design class structures.

Edexcel A-Level 课程希望你理解 OOP 的优势,例如封装、继承和多态。理解这些特性为何重要,为应对更大的编程项目和考试中要求比较范式或设计类结构的问题奠定了基础。


2. Classes and Objects | 类与对象

A class is a blueprint that defines the attributes and methods an object will possess. An object is a specific instance of a class, containing actual data. For example, a class Student might declare attributes like name and grade, along with a method calculate_average(). Each student object then holds values for its own name and grade. The separation of class definition and instantiation is central to OOP.

类是定义对象将拥有哪些属性和方法的蓝图。对象是类的一个具体实例,包含实际数据。例如,类 Student 可能声明 namegrade 等属性,以及一个 calculate_average() 方法。然后每个学生对象都保存自己的姓名和成绩值。类定义与实例化的分离是 OOP 的核心。

In Python, a class is created using the class keyword, and objects are instantiated by calling the class as if it were a function. Below is a simple illustration.

在 Python 中,使用 class 关键字创建类,并通过像调用函数一样调用类来实例化对象。下面是一个简单示例。


class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def show_info(self):
        return f"{self.name} achieved grade {self.grade}"

s1 = Student("Ali", "A")
print(s1.show_info())

上面的代码定义了一个 Student 类,其构造函数 __init__ 初始化属性。方法 show_info 返回格式化的字符串。然后创建对象 s1 并调用其方法。这种封装数据和行为的方式使代码更易读且可重用。


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

Encapsulation means bundling data and the methods that manipulate it inside a single unit (the class). A key goal is data hiding – restricting access to an object’s internal state. Typically, attributes are declared private, and public getter and setter methods provide controlled access. This prevents accidental corruption and makes the code easier to refactor.

封装意味着将数据和操作这些数据的方法捆绑在一个单元(类)中。一个关键目标是数据隐藏——限制对对象内部状态的访问。通常,属性被声明为私有的,而公共的 getter 和 setter 方法提供受控访问。这可以防止意外损坏,并使代码更易于重构。

Python does not enforce strict access modifiers like Java, but a common convention is to prefix a name with double underscores to make it private through name mangling. Consider a BankAccount class:

Python 不像 Java 那样强制执行严格的访问修饰符,但常见的约定是使用双下划线作为名称前缀,通过名称改写使其成为私有。考虑一个 BankAccount 类:


class BankAccount:
    def __init__(self, initial):
        self.__balance = initial

    def get_balance(self):
        return self.__balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

Here the attribute __balance is private. External code cannot directly access or modify it; instead, it must use the public methods. This guarantees that any deposit passes validation (amount > 0) and maintains data integrity.

这里属性 __balance 是私有的。外部代码无法直接访问或修改它;而必须使用公共方法。这保证了任何存款都通过验证(amount > 0)并保持数据完整性。


4. Inheritance and Code Reuse | 继承与代码复用

Inheritance allows a new class (subclass/derived class) to extend an existing class (superclass/base class). The subclass automatically inherits all attributes and methods, which it can then override or supplement. This promotes code reuse and establishes an “is-a” relationship. For example, a SportsCar is a Car with extra features.

继承允许新类(子类/派生类)扩展现有类(超类/基类)。子类自动继承所有属性和方法,然后可以覆盖或补充它们。这促进了代码复用并建立了“是一个”关系。例如,SportsCar 是带有额外功能的 Car

In Python, inheritance is specified by placing the parent class name in parentheses. The method resolution order (MRO) determines which method is called when there are multiple levels. The super() function is used to invoke the parent constructor or methods.

在 Python 中,通过将父类名称放在括号中来指定继承。方法解析顺序(MRO)确定有多层时调用哪个方法。使用 super() 函数调用父构造函数或方法。


class Vehicle:
    def __init__(self, make):
        self.make = make

class Car(Vehicle):
    def __init__(self, make, model):
        super().__init__(make)
        self.model = model

    def details(self):
        return f"{self.make} {self.model}"

The Car class inherits make from Vehicle and adds model. By calling super().__init__(make), we reuse the parent’s initialisation logic, avoiding duplication.

Car 类从 Vehicle 继承了 make 并添加了 model。通过调用 super().__init__(make),我们重用了父类的初始化逻辑,避免了重复。


5. Polymorphism and Dynamic Binding | 多态与动态绑定

Polymorphism (Greek for “many forms”) allows objects of different types to respond to the same method call in their own specialised way. The most common implementation is method overriding, where a subclass redefines a method of the superclass. At runtime, dynamic binding selects the appropriate method based on the actual object, not the reference type. This makes code more flexible and extensible.

多态(希腊语中的“多种形态”)允许不同类型的对象以自己的专业方式响应相同的方法调用。最常见的实现是方法重写,即子类重新定义超类的方法。在运行时,动态绑定根据实际对象而非引用类型选择适当的方法。这使代码更加灵活和可扩展。

A classic example uses a base Shape class and derived Circle, Square classes, each with its own draw() method.

一个经典的例子使用基类 Shape 以及派生的 CircleSquare 类,每个类都有自己的 draw() 方法。


class Shape:
    def draw(self):
        pass

class Circle(Shape):
    def draw(self):
        return "Drawing a circle"

class Square(Shape):
    def draw(self):
        return "Drawing a square"

shapes = [Circle(), Square()]
for s in shapes:
    print(s.draw())

Even though the loop variable s is typed as Shape, the correct overridden method is invoked for each object. This polymorphic behaviour simplifies code that needs to handle multiple types uniformly.

尽管循环变量 s 的类型是 Shape,但为每个对象调用了正确的重写方法。这种多态行为简化了需要统一处理多种类型的代码。


6. Abstraction and Abstract Classes | 抽象与抽象类

Abstraction focuses on revealing only essential functionality and hiding complex implementation. In OOP, an abstract class serves as a partial blueprint: it cannot be instantiated and may include abstract methods that lack a body. Subclasses are forced to provide concrete implementations, guaranteeing a consistent interface across a family of types.

抽象侧重于仅揭示基本功能并隐藏复杂实现。在 OOP 中,抽象类作为部分蓝图:它不能被实例化,可能包括没有主体的抽象方法。子类被迫提供具体实现,从而保证一类类型具有一致的接口。

Python’s abc module supports abstract base classes. Using the @abstractmethod decorator, you state that a method must be overridden. This is particularly useful for defining frameworks.

Python 的 abc 模块支持抽象基类。使用 @abstractmethod 装饰器,你声明一个方法必须被重写。这在定义框架时尤其有用。


from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Bark"

# a = Animal()  # this would raise TypeError
d = Dog()
print(d.sound())

Attempting to instantiate Animal raises an error because it is abstract. The Dog class fulfills the contract by implementing sound(). This guarantees that all animal subclasses speak in their own way.

尝试实例化 Animal 会引发错误,因为它是抽象的。Dog 类通过实现 sound() 满足了契约。这保证了所有动物的子类都以自己的方式发声。


7. Interfaces and Multiple Inheritance | 接口与多重继承

An interface defines a set of method signatures that implementing classes must fulfil. While languages like Java have a dedicated interface keyword, Python achieves the same effect through abstract classes containing only abstract methods. Another powerful feature is multiple inheritance, where a class inherits from more than one parent. This can model complex relationships but brings the risk of the “diamond problem”, where the method lookup path becomes ambiguous.

接口定义了实现类必须满足的一组方法签名。虽然 Java 等语言有专用的 interface 关键字,但 Python 通过仅包含抽象方法的抽象类达到同样的效果。另一个强大的特性是多重继承,即一个类继承自多个父类。这可以模拟复杂的关系,但也会带来“钻石问题”的风险,即方法查找路径变得模糊。

Python’s C3 linearization algorithm resolves the diamond problem by providing a consistent MRO. Mixin classes (small, reusable classes that add behaviours) are a common and safe pattern for multiple inheritance.

Python 的 C3 线性化算法通过提供一致的 MRO 解决了钻石问题。Mixin 类(添加行为的小型可重用类)是多重继承的一种常见且安全的模式。


class Loggable:
    def log(self, msg):
        print(f"LOG: {msg}")

class Database:
    def save(self, data):
        print("Saving", data)

class App(Loggable, Database):
    def run(self):
        self.log("App started")
        self.save("result")

App inherits both Loggable and Database, combining their capabilities. Python resolves method calls from left to right in the inheritance tuple.

App 同时继承了 LoggableDatabase,组合了它们的功能。Python 按照继承元组中从左到右的顺序解析方法调用。


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

Relationships between objects are modelled using association, aggregation, and composition. These describe how strongly objects depend on each other and affect system design and memory management.

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading