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(同微信)

Comments

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

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

Exit mobile version