Object-Oriented Programming in Python | Python 面向对象编程

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

Object-Oriented Programming (OOP) is a paradigm that organises code around ‘objects’ rather than functions and logic. It bundles data (attributes) and the procedures (methods) that operate on that data into single units known as classes. Mastery of OOP is essential for A-Level Edexcel Computer Science, as it underpins modular, reusable, and maintainable software design. This article covers the core principles—encapsulation, inheritance, polymorphism, and abstraction—with clear Python examples aligned to the Edexcel specification.

面向对象编程(OOP)是一种围绕“对象”而非函数和逻辑来组织代码的范式。它将数据(属性)和操作数据的过程(方法)捆绑在一起,形成称为类的单一单元。掌握OOP对于A-Level Edexcel计算机科学至关重要,因为它是模块化、可重用和可维护软件设计的基础。本文涵盖了核心原则——封装、继承、多态和抽象——并配有符合Edexcel考试大纲的清晰Python示例。

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

Object-Oriented Programming models real-world entities as objects that have state (attributes) and behaviour (methods). Unlike procedural programming, which separates data from actions, OOP keeps them together, making complex systems easier to manage and extend. Classes act as blueprints from which individual objects are instantiated, promoting code reuse and logical structure.

面向对象编程将现实世界中的实体建模为具有状态(属性)和行为(方法)的对象。与将数据与操作分离的过程式编程不同,OOP将二者保持在一起,使得复杂系统更易于管理和扩展。类作为蓝图,从中实例化出各个对象,促进了代码重用和逻辑结构。

In the Edexcel specification, you are expected to understand classes, objects, inheritance, polymorphism, and the advantages of OOP over procedural approaches. Python is particularly well-suited because it supports multiple programming paradigms, including OOP, with clear syntax.

在Edexcel大纲中,你需要理解类、对象、继承、多态以及OOP相对于过程式方法的优势。Python特别适合,因为它支持包括OOP在内的多种编程范式,且语法清晰。


2. Classes and Objects | 类与对象

A class is a user-defined data type that encapsulates attributes and methods. An object is an instance of a class. For example, a class Student might have attributes like name and grade, and methods like calculate_average(). Each object created from Student holds its own copy of the attributes, allowing multiple unique students to coexist in memory.

类是一种用户定义的数据类型,它封装了属性和方法。对象是类的实例。例如,一个Student类可能具有namegrade等属性,以及calculate_average()等方法。从Student创建的每个对象都持有自己的一份属性副本,允许多个独特的学生在内存中共存。

Defining a class in Python uses the class keyword. Instantiation simply calls the class name as if it were a function, which triggers the constructor. The following snippet shows a minimal class definition and object creation.

在Python中定义类使用class关键字。实例化只需像调用函数一样调用类名,这将触发构造函数。以下片段展示了一个最简单的类定义和对象创建。

class Student:
    pass

s1 = Student()  # s1 is an object of type Student

Objects can be assigned to variables, passed as arguments, and stored in data structures, making them first-class citizens in Python. The exam may ask you to trace object creation or identify valid class definitions.

对象可以赋给变量、作为参数传递并存储在数据结构中,使它们成为Python中的一等公民。考试可能会要求你回溯对象的创建或识别有效的类定义。


3. Attributes and Methods | 属性与方法

Attributes are variables that belong to an object or class; methods are functions defined inside a class. Instance attributes are typically initialised inside the constructor using self, which refers to the current object. Methods must also take self as their first parameter so they can access the object’s data.

属性是属于对象或类的变量;方法是在类内部定义的函数。实例属性通常在构造函数内部使用self进行初始化,self指向当前对象。方法也必须将self作为第一个参数,以便它们能够访问对象的数据。

Consider a BankAccount class with attributes account_number and balance, and a method deposit(amount). The self parameter distinguishes instance methods from static functions. Without self, the method cannot modify the object’s state.

考虑一个BankAccount类,具有account_numberbalance属性,以及一个deposit(amount)方法。self参数将实例方法与静态函数区分开来。如果没有self,方法就无法修改对象的状态。

class BankAccount:
    def __init__(self, acc_num, initial_balance):
        self.account_number = acc_num
        self.balance = initial_balance

    def deposit(self, amount):
        self.balance += amount

    def display_balance(self):
        return f"Account {self.account_number}: £{self.balance}"

In Edexcel questions, you may need to identify the difference between class attributes (shared) and instance attributes (per-object). This distinction is crucial for understanding memory usage and data integrity.

在Edexcel考题中,你可能需要区分类属性(共享)和实例属性(每个对象独有)。这一区别对于理解内存使用和数据完整性至关重要。


4. The Constructor Method (__init__) | 构造函数 (__init__)

The __init__ method is a special method automatically called when a new object is instantiated. Its purpose is to initialise the object’s attributes with starting values. Python uses double underscores (dunder) to indicate magic methods. The constructor can accept parameters other than self, which are then passed during instantiation.

__init__方法是一个特殊的方法,在创建新对象时自动调用。其目的是用初始值初始化对象的属性。Python使用双下划线(dunder)来表示魔术方法。构造函数除了self外还可以接受其他参数,这些参数在实例化时传入。

For instance, when executing acc = BankAccount('12345', 500), Python calls BankAccount.__init__(acc, '12345', 500). The parameter list of __init__ therefore defines the required arguments for object creation. Omitting required arguments raises a TypeError.

例如,当执行acc = BankAccount('12345', 500)时,Python会调用BankAccount.__init__(acc, '12345', 500)。因此__init__的参数列表定义了创建对象所需的参数。缺少必要参数会引发TypeError

Concept Description
self Reference to the instance being created; must be the first parameter.
__init__ Constructor; executed once per new object to set initial state.
Default arguments Can be used in __init__ to make some parameters optional.

The table summarises the constructor’s role. Remember that __init__ is not the true constructor; __new__ actually creates the object, but __init__ is the initialiser typically used. At A-Level, you only need to use __init__.

上表总结了构造函数的作用。请记住,__init__并非真正的构造器;__new__实际上创建对象,但__init__是常用的初始化器。在A-Level阶段,你只需使用__init__


5. Encapsulation and Access Modifiers | 封装与访问修饰符

Encapsulation hides the internal state of an object and only exposes a controlled interface via methods. In Python, encapsulation relies on naming conventions rather than strict keywords like private or public. A single underscore prefix (_) signals that an attribute or method is intended for internal use (protected), while a double underscore (__) triggers name mangling to make it harder to access from outside (private).

封装隐藏了对象的内部状态,仅通过方法暴露受控接口。在Python中,封装依赖于命名约定,而非像privatepublic这样的严格关键字。单下划线前缀(_)表示属性或方法仅供内部使用(受保护),双下划线(__)会触发名称改写,使其更难从外部访问(私有)。

Name mangling changes __balance to _ClassName__balance, preventing accidental access but not intentional hacking. Getters and setters are often used to provide controlled access, often implemented with the @property decorator for a more Pythonic style.

名称改写将__balance更改为_ClassName__balance,防止意外访问,但无法阻止故意攻击。通常使用getter和setter来提供受控访问,常用@property装饰器来实现更Pythonic的风格。

class SecureAccount:
    def __init__(self, balance):
        self.__balance = balance  # private

    def get_balance(self):
        return self.__balance

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

Encapsulation is a key OOP principle. It protects data integrity by ensuring that attributes are only modified through well-defined methods, which can include validation. Edexcel requires you to explain the benefits of encapsulation, such as easier maintenance, reduced side effects, and improved security.

封装是OOP的关键原则。它通过确保属性仅通过定义良好的方法(可以包含验证)进行修改来保护数据完整性。Edexcel要求你解释封装的好处,例如更易于维护、减少副作用和提高安全性。


6. Inheritance: Extending Classes | 继承:扩展类

Inheritance allows a new class (child/derived) to absorb the attributes and methods of an existing class (parent/base), facilitating code reuse and the creation of hierarchical relationships. In Python, inheritance is specified by placing the parent class name in parentheses after the child class name: class Child(Parent):.

继承允许新类(子类/派生类)吸收现有类(父类/基类)的属性和方法,促进了代码重用和层次关系的建立。在Python中,继承通过在子类名后面的括号中放置父类名来指定:class Child(Parent):

A child class can add new attributes/methods or override existing ones. Python supports multiple inheritance (a class inheriting from more than one parent), but Edexcel focuses on single inheritance for clarity. The built-in issubclass() and isinstance() functions check inheritance relationships.

子类可以添加新的属性/方法或重写现有的方法。Python支持多重继承(一个类继承自多个父类),但Edexcel为清晰起见侧重于单继承。内置的issubclass()isinstance()函数用于检查继承关系。

For example, a Dog class might inherit from an Animal class, gaining a eat() method while adding a bark() method. This models the ‘is-a’ relationship: a Dog is an Animal. The diagram below maps the concept to a simple taxonomy.

例如,一个Dog类可能继承自Animal类,获得eat()方法的同时添加bark()方法。这模拟了“是一个”的关系:狗是一种动物。下面的图表将该概念映射到一个简单的分类法。

class Animal:
    def eat(self):
        print("Eating...")

class Dog(Animal):
    def bark(self):
        print("Woof!")

d = Dog()
d.eat()   # inherited
d.bark()  # defined in Dog

When answering exam questions, always identify the parent class and explain how inheritance reduces duplication. You may also be asked to translate inheritance hierarchies between UML class diagrams and code.

在回答考题时,一定要指出父类,并解释继承如何减少重复。你还可能被要求将继承层次结构在UML类图和代码之间进行转换。


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

Polymorphism allows objects of different classes to be treated as objects of a common superclass. The same method call can produce different behaviours depending on the object’s class. This is typically achieved through method overriding, where a subclass provides a specific implementation of a method defined in its superclass.

多态允许将不同类的对象当作公共超类的对象来处理。同一个方法调用可以根据对象的类产生不同的行为。这通常通过方法重写来实现,即子类为其超类中定义的方法提供特定的实现。

Python’s dynamic typing makes polymorphism natural; you don’t need a special interface. For example, a function that expects an Animal parameter can receive a Dog or a Cat, and calling speak() will invoke the correct overridden version.

Python的动态类型使得多态变得自然;无需特殊的接口。例如,一个期望Animal参数的函数可以接收DogCat,调用speak()将调用正确的重写版本。

class Cat(Animal):
    def speak(self):
        print("Meow")

def make_sound(animal):
    animal.speak()

make_sound(Dog())   # Woof!
make_sound(Cat())   # Meow

The Edexcel specification often asks candidates to describe polymorphism and provide examples. A common exam scenario involves a collection of shape objects (Circle, Rectangle) that each implement a draw() method differently, demonstrating polymorphic behaviour.

Edexcel大纲经常要求考生描述多态并提供示例。一个常见的考试场景涉及一组形状对象(圆形、矩形),它们各自以不同的方式实现draw()方法,从而展示多态行为。


8. Method Overriding and super() | 方法重写与 super()

When a subclass defines a method with the same name as one in its parent, it overrides the parent method. The overridden version is used for instances of the subclass, but the parent version is still accessible via the super() function. super() returns a proxy object that delegates calls to the parent class, enabling cooperative multiple inheritance.

当子类定义的方法与其父类中的方法同名时,它会重写父类方法。重写的版本用于子类的实例,但父类版本仍可通过super()函数访问。super()返回一个代理对象,将调用委托给父类,从而实现了协作式多重继承。

Overriding is essential for customising behaviour. A common pattern is to extend rather than completely replace the parent method: call super().method() to execute the parent logic, then add subclass-specific code. This avoids code duplication and maintains the parent’s contract.

重写对于定制行为至关重要。一个常见的模式是扩展而非完全替换父类方法:调用super().method()来执行父类逻辑,然后添加子类特定的代码。这避免了代码重复,并维护了父类的契约。

class Robot:
    def work(self):
        print("Performing general tasks")

class CleaningRobot(Robot):
    def work(self):
        super().work()   # call parent version
        print("Now vacuuming the floor")

In the exam, you might be asked to trace the output of a program that uses super() or to explain why overriding is necessary. Remember that super() in Python works with the Method Resolution Order (MRO) to determine the correct parent class, especially in diamond inheritance structures.

在考试中,你可能会被要求回溯使用super()的程序的输出,或解释为什么需要重写。请记住,Python中的super()根据方法解析顺序(MRO)来确定正确的父类,尤其是在菱形继承结构中。


9. Abstract Base Classes (ABC) | 抽象基类 (ABC)

An abstract base class defines a common interface for a group of subclasses without providing a complete implementation. It declares one or more abstract methods that must be overridden in concrete subclasses. In Python, the abc module provides the ABC class and the @abstractmethod decorator to enforce this contract.

抽象基类为一组子类定义了一个通用接口,但并不提供完整的实现。它声明了一个或多个必须由具体子类重写的抽象方法。在Python中,abc模块提供了ABC类和@abstractmethod装饰器来强制执行这一契约。

Attempting to instantiate a class that inherits from ABC without overriding all abstract methods raises a TypeError. This is a form of polymorphism enforcement and is particularly useful in large systems to ensure that derived classes adhere to a specified template.

尝试实例化一个继承自ABC但未重写所有抽象方法的类会引发TypeError。这是一种多态强制形式,在大型系统中特别有用,可确保派生类遵循指定的模板。

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side * self.side

Edexcel may include questions that assess your understanding of what an abstract class is and why it is used. Key benefits include defining a consistent API, preventing direct instantiation of incomplete classes, and simplifying maintenance through enforced method signatures.

Edexcel可能包含考查你对抽象类是什么以及为何使用它的理解的题目。主要好处包括定义一致的API、防止直接实例化不完整的类,以及通过强制方法签名来简化维护。


10. Composition vs Inheritance | 组合与继承的比较

While inheritance models an ‘is-a’ relationship, composition models a ‘has-a’ relationship by including instances of other classes as attributes. Composition is often favoured over deep inheritance hierarchies because it provides greater flexibility and reduces coupling. You can change behaviour at runtime by swapping composed objects.

继承模拟“是一个”关系,而组合通过将其他类的实例作为属性来模拟“有一个”关系。组合通常比深层继承层次结构更受青睐,因为它提供了更大的灵活性并减少了耦合。可以通过交换组合对象在运行时更改行为。

Edexcel stresses choosing between inheritance and composition based on the problem. For example, a Library class should contain a list of Book objects (composition), not inherit from Book. The principle of ‘favour composition over inheritance’ is a design guideline that reduces fragile base class problems.

Edexcel强调根据问题在继承和组合之间做出选择。例如,一个Library类应该包含一个Book对象列表(组合),而不是继承自Book。“优先使用组合而非继承”的原则是一条设计准则,可以减少脆弱的基类问题。

Inheritance Composition
Tight coupling; child depends on parent implementation Loose coupling; objects interact via well-defined interfaces
Static relationship defined at compile time Dynamic relationship can be changed at runtime
Can lead to complex hierarchies Encourages simpler, more modular design

Exam questions might ask you to evaluate a given class diagram and suggest whether inheritance or composition is more appropriate. Be prepared to justify your choice with reference to maintainability, reusability, and clarity.

考题可能会要求你评估给定的类图,并建议继承或组合哪种更合适。请准备好参照可维护性、可重用性和清晰性来证明你的选择。


11. Practical Example: A School Management System | 实例:学校管理系统

Let’s consolidate OOP concepts by designing a simplified school system. We have a base class Person with attributes name and age. Two subclasses, Teacher and Student, extend Person and add specific attributes. A Classroom class uses composition to contain a teacher and a list of students, demonstrating both relationships.

让我们通过设计一个简化的学校系统来巩固OOP概念。我们有一个基类Person,具有nameage属性。两个子类TeacherStudent继承自Person并添加了特定的属性。一个Classroom类使用组合来包含一位教师和一个学生列表,展示了两种关系。

Class definitions:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def introduce(self):
        return f"My name is {self.name}."

class Teacher(Person):
    def __init__(self, name, age, subject):
        super().__init__(name, age)
        self.subject = subject
    def teach(self):
        return f"Teaching {self.subject}"

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id
    def study(self):
        return f"{self.name} is studying."

class Classroom:
    def __init__(self, room_number, teacher):
        self.room_number = room_number
        self.teacher = teacher
        self.students = []
    def add_student(self, student):
        self.students.append(student)
    def roll_call(self):
        names = [s.name for s in self.students]
        return f"Teacher: {self.teacher.name}, Students: {', '.join(names)}"

This example illustrates inheritance (Teacher and Student from Person), composition (Classroom has a Teacher and multiple Student objects), and polymorphism—both Teacher and Student override introduce() if desired, but here they inherit the base version. It also shows the use of super() in constructors.

这个例子展示了继承(TeacherStudent继承自Person)、组合(Classroom拥有一个Teacher和多个Student对象)以及多态——如果需要,TeacherStudent都可以重写introduce(),但这里它们继承了基类版本。还展示了构造函数中super()的使用。

Running a test gives:

t = Teacher("Ms. Smith", 35, "Maths")
s1 = Student("Alice", 16, "S1001")
s2 = Student("Bob", 17, "S1002")
room = Classroom("B12", t)
room.add_student(s1)
room.add_student(s2)
print(room.roll_call())
# Output: Teacher: Ms. Smith, Students: Alice, Bob

Such integrated examples are common in Edexcel coursework and paper-based scenarios. You should be able to identify and justify the OOP techniques used.

这种综合示例在Edexcel的课程作业和试卷场景中很常见。你应该能够识别并论证所使用的OOP技术。


12. Conclusion & Key Takeaways | 总结与要点

Object-Oriented Programming in Python revolves around binding data and behaviour into classes, enabling modular, secure, and extensible software. The four pillars—encapsulation, inheritance, polymorphism, and abstraction—provide a powerful toolkit for solving complex problems. Understanding the subtleties of self, constructors, access modifiers, and method overriding is vital for exam success.

Python中的面向对象编程围绕将数据和行为绑定到类中展开,从而实现模块化、安全且可扩展的软件。四大支柱——封装、继承、多态和抽象——为解决复杂问题提供了强大的工具包。理解self、构造函数、访问修饰符和方法重写的细微差别对于考试成功至关重要。

  • Use classes and objects to model real-world entities.
  • Employ encapsulation to protect data and define clear interfaces.
  • Leverage inheritance to reuse code and establish logical hierarchies.
  • Apply polymorphism and abstraction to write flexible, maintainable programs.
  • Prefer composition over inheritance when the relationship is ‘has-a’ to avoid tight coupling.
  • 使用类和对象来模拟现实世界实体。
  • 运用封装保护数据并定义清晰的接口。
  • 利用继承重用代码并建立逻辑层次结构。
  • 应用多态和抽象来编写灵活、可维护的程序。
  • 当关系为“有一个”时,优先使用组合而非继承,以避免紧耦合。

Review the code examples and ensure you can independently write class definitions, implement inheritance, and explain the advantages of each OOP principle. Practice past-paper questions that require error-spotting in class definitions or evaluating design choices.

复习代码示例,确保你能够独立编写类定义、实现继承并解释每种OOP原则的优点。练习往年试卷中要求找出类定义错误或评估设计选择的题目。

Published by TutorHao | Programming Revision Series | aleveler.com

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

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