📚 Object-Oriented Programming in Python: Classes, Inheritance and Polymorphism | Python 面向对象编程:类、继承与多态
Object-oriented programming (OOP) is a core topic in the Edexcel A-Level Computer Science specification, particularly within Topic 4: Programming. This article explains the key OOP concepts in Python: classes, objects, encapsulation, inheritance, and polymorphism.
面向对象编程(OOP)是 Edexcel A-Level 计算机科学规范中的核心主题之一,尤其是第 4 单元:编程。本文解释 Python 中的关键 OOP 概念:类、对象、封装、继承和多态。
1. Introduction to Object-Oriented Programming | 面向对象编程简介
Object-oriented programming is a paradigm that organises code around 'objects' rather than functions and logic alone. An object bundles data and the functions that operate on that data into a single unit.
面向对象编程是一种围绕“对象”而非仅函数和逻辑组织代码的编程范式。对象将数据以及操作这些数据的函数捆绑为一个单元。
The main benefits of OOP include easier maintenance, code reuse through inheritance, and the ability to model real-world entities more naturally. For A-Level exams, you need to explain these advantages and identify the building blocks: class, object, attribute, method, constructor, encapsulation, inheritance, and polymorphism.
OOP 的主要优点包括更易于维护、通过继承实现代码复用,以及能够更自然地模拟现实世界实体。对于 A-Level 考试,你需要解释这些优点,并识别基本构建块:类、对象、属性、方法、构造器、封装、继承和多态。
2. Classes and Objects in Python | Python 中的类与对象
A class is a blueprint or template for creating objects. An object is an instance of a class. For example, the class Student defines the general properties and behaviours of all students, while each individual student is an object of that class.
类是创建对象的蓝图或模板。对象是类的一个实例。例如,Student 类定义了所有学生的通用属性和行为,而每个具体的学生则是该类的一个对象。
In Python, you define a class using the class keyword followed by the class name and a colon. The body of the class contains method definitions with an indented block. The simplest class can be written as class Student: pass.
在 Python 中,使用 class 关键字后跟类名和冒号来定义类。类的主体包含缩进的方法定义。最简单的类可以写作 class Student: pass。
- Class = blueprint (e.g. Student)
- Object = a real instance (e.g. Alice, Bob)
- Class = 蓝图(例如学生)
- Object = 真实实例(例如 Alice、Bob)
3. The __init__ Constructor and self | __init__ 构造器与 self
The __init__ method is a special constructor that runs automatically when an object is created. It initialises the object's attributes with values passed as arguments.
__init__ 方法是一个特殊的构造器,在创建对象时自动运行。它用传入的参数值初始化对象的属性。
Inside every instance method, the first parameter self refers to the current object. Using self.name = name stores the parameter value into the object's own attribute, so different objects keep separate data.
在每个实例方法内部,第一个参数 self 指向当前对象。使用 self.name = name 将参数值存入对象自身的属性,从而使不同对象保存各自独立的数据。
Example: def __init__(self, name, age): self.name = name; self.age = age. When you write student1 = Student('Alice', 17), Python calls Student.__init__(student1, 'Alice', 17) automatically.
示例:def __init__(self, name, age): self.name = name; self.age = age。当你编写 student1 = Student('Alice', 17) 时,Python 会自动调用 Student.__init__(student1, 'Alice', 17)。
4. Attributes and Methods | 属性与方法
Attributes are variables that belong to an object, and methods are functions that belong to an object. In a class, attributes are usually defined inside __init__, while methods are defined as functions inside the class body.
属性是属于对象的变量,方法是属于对象的函数。在类中,属性通常在 __init__ 内部定义,而方法则定义为类主体内部的函数。
There are two types of attributes: instance attributes (unique to each object, using self.) and class attributes (shared by all objects, written directly inside the class). A-level exam questions often ask you to distinguish between these.
属性有两种类型:实例属性(每个对象独有,使用 self.)和类属性(所有对象共享,直接写在类内部)。A-level 考试题经常要求区分二者。
For example, a class attribute school = 'Aleveler College' is the same for all objects, while self.name is different for each student. Accessing an attribute is done with dot notation: object.attribute.
例如,类属性 school = 'Aleveler College' 对所有对象都是相同的,而 self.name 每个学生不同。使用点号访问属性:对象.属性。
5. Encapsulation and Access Modifiers | 封装与访问修饰符
Encapsulation means hiding the internal state of an object and requiring all interaction to go through public methods. This protects data from being changed in unexpected ways and makes the code easier to debug.
封装意味着隐藏对象的内部状态,并要求所有交互都通过公共方法进行。这可以保护数据不被以意外方式更改,并使代码更易于调试。
In Python, encapsulation is implemented by naming conventions rather than strict access modifiers. A single leading underscore (_attribute) signals 'protected', while a double leading underscore (__attribute) triggers name mangling to make it harder to access from outside the class.
在 Python 中,封装通过命名约定而非严格的访问修饰符实现。单下划线前缀(_attribute)表示“受保护”,双下划线前缀(__attribute)触发名称改编,使其难以从类外部访问。
To provide controlled access, use getter and setter methods. For example, a get_age() method returns the age, and a set_age(new_age) method validates input before changing the value. The @property decorator can make getters and setters look like normal attribute access.
为了提供受控访问,使用 getter 和 setter 方法。例如,get_age() 方法返回年龄,set_age(new_age) 方法在更改值之前验证输入。使用 @property 装饰器可以让 getter 和 setter 看起来像普通的属性访问。
6. Inheritance: Building Class Hierarchies | 继承:构建类层次结构
Inheritance allows a new class (child or subclass) to reuse the attributes and methods of an existing class (parent or superclass). This supports code reuse and models 'is-a' relationships, such as a Dog is an Animal.
继承允许新类(子类)重用现有类(父类或超类)的属性和方法。这支持代码复用,并模拟“is-a”关系,例如 Dog 是一个 Animal。
In Python, a subclass is defined by placing the parent class name in parentheses: class Dog(Animal):. The subclass automatically inherits all methods and attributes from the parent, but it can also add new ones or override existing ones.
在 Python 中,通过在括号中放置父类名称来定义子类:class Dog(Animal):。子类自动继承父类的所有方法和属性,但它也可以添加新方法或覆盖现有方法。
Exam questions may ask you to identify the superclass, subclass, and inherited members from a given code snippet, or to write a subclass that extends a given parent correctly.
考试题可能会要求你从给定代码片段中识别超类、子类和继承的成员,或者编写一个正确扩展给定父类的子类。
7. Method Overriding and the super() Function | 方法重写与 super() 函数
Method overriding occurs when a subclass defines a method with the same name as a method in its parent class. The subclass version replaces the parent version for objects of the subclass, allowing more specific behaviour.
方法重写发生在子类定义了与其父类中某个方法同名的方法时。对于子类的对象,子类版本会替换父类版本,从而允许更具体的行为。
If you need to call the parent class's version from within the overridden method, use the super() function. For example, super().__init__(name) calls the parent constructor before adding subclass-specific initialisation.
如果需要在重写的方法内部调用父类的版本,请使用 super() 函数。例如,super().__init__(name) 在添加子类特定的初始化之前调用父类构造器。
Using super() avoids duplicating code and ensures that the parent's initialisation or validation still runs. This is a common pattern in object-oriented Python and appears frequently in A-level coding questions.
使用 super() 可以避免重复代码,并确保父类的初始化或验证仍会运行。这是面向对象 Python 中的常见模式,经常出现在 A-level 编程题中。
8. Polymorphism and Duck Typing | 多态与鸭子类型
Polymorphism means 'many forms'. In OOP, it allows different classes to provide their own implementation of the same method name, so the same code can work with objects of different types.
多态意味着“多种形态”。在 OOP 中,它允许不同的类为相同的方法名提供各自的实现,因此同一代码可以适用于不同类型的对象。
Python uses duck typing: if an object has the required method, it can be used regardless of its class. The saying 'if it walks like a duck and quacks like a duck, then it is a duck' summarises this idea.
Python 使用鸭子类型:如果一个对象具有所需的方法,那么无论它属于哪个类都可以使用。谚语“如果它走路像鸭子,叫声像鸭子,那么它就是鸭子”概括了这一思想。
For example, both Circle and Square classes may define an area() method. A function that calls shape.area() works with either class, demonstrating polymorphic behaviour without inheritance.
例如,Circle 和 Square 类都可以定义 area() 方法。调用 shape.area() 的函数对两个类都适用,展示了无需继承的多态行为。
9. Abstract Base Classes (ABCs) | 抽象基类(ABC)
An abstract base class is a class that cannot be instantiated; its purpose is to define a common interface for subclasses. In Python, the abc module provides the ABC class and the @abstractmethod decorator.
抽象基类是不能被实例化的类;其目的是为子类定义通用接口。在 Python 中,abc 模块提供了 ABC 类和 @abstractmethod 装饰器。
Any subclass of an abstract class must override all abstract methods, otherwise the subclass also becomes abstract and cannot be instantiated. This enforces a contract for all derived classes.
抽象类的任何子类都必须重写所有抽象方法,否则子类也会变成抽象类且无法实例化。这为所有派生类强制执行了一个契约。
For Edexcel A-Level, you should be able to recognise the purpose of abstract classes and explain why they are useful in designing large programs with consistent interfaces.
对于 Edexcel A-Level,你应该能够识别抽象类的用途,并解释为什么它们在设计具有一致接口的大型程序时很有用。
10. OOP vs Procedural Programming: Exam Perspective | OOP 与过程式编程:考试视角
Procedural programming organises code as a sequence of instructions and functions, while OOP organises code as interacting objects. Both paradigms can solve the same problems, but OOP is often preferred for large, complex systems because it improves modularity and maintainability.
过程式编程将代码组织为一系列指令和函数,而 OOP 将代码组织为相互交互的对象。两种范式都可以解决相同的问题,但 OOP 通常更适合大型复杂系统,因为它提高了模块化和可维护性。
In exam questions, you may be asked to compare the two paradigms, identify which is more suitable for a given scenario, or convert a short procedural script into an object-oriented version using classes and methods.
在考试题中,你可能需要比较这两种范式,确定哪种更适合给定的场景,或者将一个简短的过程式脚本转换为使用类和方法的面向对象版本。
Remember the key terms and their definitions: class, object, attribute, method, constructor, inheritance, polymorphism, encapsulation, and abstract class. Practise writing short Python class definitions by hand, because Edexcel coding questions often expect you to write or complete code in the exam.
记住关键术语及其定义:类、对象、属性、方法、构造器、继承、多态、封装和抽象类。练习手写简短的 Python 类定义,因为 Edexcel 编程题常要求你在考试中编写或补全代码。
Published by TutorHao | Computer Science Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)

或截图后用「扫一扫 → 相册」选择本图