面向对象的三大特性与类图

server/2024/10/18 8:26:27/

1. 面向对象编程的三大特点

Object-oriented programming (OOP) is a paradigm centered around the concept of objects, which can contain data and code to manipulate that data. The three major characteristics of object-oriented programming are encapsulation, inheritance, and polymorphism. Below are Python examples illustrating each characteristic:面向对象编程(OOP)是一种以对象概念为中心的范式,对象可以包含数据和操作该数据的代码。面向对象编程的三大特点是封装、继承、多态。下面是说明每个特征的 Python 示例:

1. Encapsulation 封装

Encapsulation refers to bundling data (attributes) and methods (functions) that operate on the data into a single unit, called an object. It also involves restricting direct access to some of the object’s components, which is a means of preventing accidental interference and misuse of the data.封装是指将数据(属性)和对数据进行操作的方法(函数)捆绑到一个称为对象的单元中。它还涉及限制对某些对象组件的直接访问,这是防止意外干扰和误用数据的一种方法。

Example:

python">class Car:def __init__(self, make, model, year):self.make = makeself.model = modelself.year = yearself.__mileage = 0  # Private attributedef drive(self, miles):if miles > 0:self.__mileage += milesdef get_mileage(self):return self.__mileage# Usage
my_car = Car("Toyota", "Corolla", 2020)
my_car.drive(100)
print(my_car.get_mileage())  # Output: 100

2. Inheritance 继承

Inheritance is a mechanism where a new class inherits attributes and methods from an existing class. The new class, called a subclass or derived class, can add new attributes and methods or override existing ones.继承是一种新类从现有类继承属性和方法的机制。新类称为子类或派生类,可以添加新的属性和方法或覆盖现有的属性和方法。

Example:

python">class Animal:def __init__(self, name):self.name = namedef speak(self):raise NotImplementedError("Subclass must implement abstract method")class Dog(Animal):def speak(self):return f"{self.name} says Woof!"class Cat(Animal):def speak(self):return f"{self.name} says Meow!"# Usage
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak())  # Output: Buddy says Woof!
print(cat.speak())  # Output: Whiskers says Meow!

3. Polymorphism 多态

Polymorphism allows methods to do different things based on the object it is acting upon, even if they share the same name. This can be achieved through method overriding (inherited classes override methods) or through interfaces that different classes implement.多态性允许方法根据其所作用的对象执行不同的操作,即使它们共享相同的名称。这可以通过方法重写(继承类重写方法)或通过不同类实现的接口来实现。

Example:

python">class Bird:def __init__(self, name):self.name = namedef fly(self):return f"{self.name} is flying."class Penguin(Bird):def fly(self):return f"{self.name} can't fly but can swim."# Usage
birds = [Bird("Sparrow"), Penguin("Pingu")]for bird in birds:print(bird.fly())
# Output:
# Sparrow is flying.
# Pingu can't fly but can swim.

In these examples, encapsulation is demonstrated by the Car class where the mileage is a private attribute. Inheritance is shown through the Animal class, which is the parent class for Dog and Cat. Polymorphism is illustrated with the Bird and Penguin classes, where the same method fly behaves differently depending on the object.在这些示例中,封装由 Car 类演示,其中里程是私有属性。继承通过 Animal 类显示,该类是 DogCat 的父类。多态性通过 BirdPenguin 类进行说明,其中相同的方法 fly 根据对象的不同而表现不同。

2. 类图的定义

A class diagram is a type of static structure diagram in the Unified Modeling Language (UML) that describes the structure of a system by showing its classes, their attributes, methods, and the relationships among the classes. Class diagrams are used extensively in software engineering for the following purposes:类图是统一建模语言 (UML) 中的一种静态结构图,它通过显示系统的类、属性、方法以及类之间的关系来描述系统的结构。类图在软件工程中广泛用于以下目的:

Purpose of Class Diagrams

  1. Visualize the Structure of a System:可视化系统的结构:

    • Class diagrams provide a visual representation of the system’s classes and their interrelationships, helping to understand the overall architecture.类图提供了系统类及其相互关系的可视化表示,有助于理解整体架构。
  2. Blueprint for Construction:

    • They serve as a blueprint for constructing the system. Developers refer to class diagrams to understand the design and implement the code accordingly.它们充当构建系统的蓝图。开发人员参考类图来理解设计并相应地实现代码。
  3. Documentation:

    • Class diagrams act as a form of documentation that can be used for future reference and maintenance. They help new developers understand the system quickly.类图充当一种文档形式,可用于将来的参考和维护。它们帮助新开发人员快速了解系统。
  4. Communication:

    • They facilitate communication among stakeholders, including developers, designers, analysts, and business people. A clear diagram can help everyone understand the system requirements and design.它们促进利益相关者之间的沟通,包括开发人员、设计师、分析师和业务人员。清晰的图可以帮助大家理解系统需求和设计。
  5. Analysis and Design:分析与设计:

    • During the analysis and design phases of a project, class diagrams help identify the system’s required classes, their attributes, and methods, ensuring a well-thought-out design.在项目的分析和设计阶段,类图有助于识别系统所需的类、它们的属性和方法,确保设计经过深思熟虑。

Components of a Class Diagram类图的组成部分

  1. Classes:

    • Represented by rectangles divided into three sections:用分为三部分的矩形表示:
      • Top section: Contains the class name.顶部部分:包含类名称。
      • Middle section: Lists the attributes.中间部分:列出属性。
      • Bottom section: Lists the methods (operations).底部部分:列出方法(操作)。
  2. Relationships:

    • Associations: Represent relationships between classes. They can include multiplicity (e.g., one-to-one, one-to-many).关联:表示类之间的关系。它们可以包括多重性(例如,一对一、一对多)。
    • Inheritance (Generalization): Represented by a solid line with a hollow triangle pointing to the parent class.继承(泛化):用一条带有指向父类的空心三角形的实线表示。
    • Aggregation/Composition: Represent whole-part relationships. Aggregation is shown with an empty diamond at the whole end, and composition with a filled diamond.聚合/组合:表示整体与部分的关系。聚集用整个末端的空菱形显示,而合成则用实心菱形显示。
    • Dependencies: Represented by a dashed line with an arrow, indicating that one class depends on another.依赖关系:用带箭头的虚线表示,表示一个类依赖于另一个类。
  3. Attributes:

    • Attributes are variables within a class, representing the properties or characteristics of the class.属性是类中的变量,表示类的属性或特征。
  4. Methods:

    • Methods are functions or operations that define the behavior of the class.方法是定义类行为的函数或操作。

Example of a Class Diagram类图示例

Here’s a simple example of a class diagram for a school management system:这是学校管理系统类图的一个简单示例:

+--------------------+          +-----------------+
|      Person        |<---------|     Teacher     |
+--------------------+          +-----------------+
| - name: String     |          | - subject: String|
| - address: String  |          +-----------------+
| - phone: String    |          | + teach()       |
+--------------------+          +-----------------+
| + getDetails()     |
+--------------------+^||
+--------------------+
|      Student       |
+--------------------+
| - studentID: String|
| - major: String    |
+--------------------+
| + study()          |
+--------------------+

Explanation:

  • Classes:

    • Person: A general class with attributes name, address, and phone, and a method getDetails. Person :具有属性 nameaddressphone 的通用类以及方法 getDetails
    • Teacher: Inherits from Person and adds the attribute subject and method teach. Teacher :继承自 Person 并添加属性 subject 和方法 teach
    • Student: Inherits from Person and adds the attribute studentID and major, and method study. Student :继承自 Person 并添加属性 studentIDmajor 以及方法 study
  • Relationships:

    • Inheritance: Teacher and Student classes inherit from the Person class.继承: TeacherStudent 类继承自 Person 类。

This simple class diagram provides a high-level overview of how these classes interact within the system, making it easier to understand and implement the system.这个简单的类图提供了这些类如何在系统内交互的高级概述,使系统更容易理解和实现。

3. Pycharm 中打开类图

To create and view class diagrams in PyCharm, you can use the built-in UML (Unified Modeling Language) support that comes with the Professional edition. Here’s a step-by-step guide on how to open and view class diagrams in PyCharm:要在 PyCharm 中创建和查看类图,您可以使用专业版附带的内置 UML(统一建模语言)支持。以下是有关如何在 PyCharm 中打开和查看类图的分步指南:

Step-by-Step Guide分步指南

  1. Open Your Project:打开您的项目:

    • Launch PyCharm and open the project for which you want to create a class diagram.启动 PyCharm 并打开要为其创建类图的项目。
  2. Navigate to the Class Diagram Tool:导航到类图工具:

    • In the Project tool window, locate the Python file or package you are interested in.在“项目”工具窗口中,找到您感兴趣的 Python 文件或包。
  3. Generate a Class Diagram:

    • Right-click on the file or package in the Project tool window.在项目工具窗口中右键单击文件或包。
    • From the context menu, select Diagrams > Show Diagram….从上下文菜单中,选择 Diagrams > Show Diagram…
  4. View the Diagram:查看图表:

    • A new tab will open displaying the UML class diagram for the selected file or package.将打开一个新选项卡,显示所选文件或包的 UML 类图。
    • You can zoom in and out of the diagram, and move around to explore different parts of it.您可以放大和缩小图表,并四处移动以探索其不同部分。
  5. Customize the Diagram:

    • You can customize the diagram to better suit your needs:您可以自定义图表以更好地满足您的需求:
      • Right-click on the diagram to access options like Show Categories, Show Fields, Show Methods, etc.右键单击图表可访问 Show CategoriesShow FieldsShow Methods 等选项。
      • Use the toolbar on the diagram window to add new classes, interfaces, and relationships.使用图表窗口上的工具栏添加新的类、接口和关系。
  6. Export the Diagram:

    • If you want to save the diagram as an image, right-click on the diagram and select Export Diagram….如果要将图表另存为图像,请右键单击图表并选择 Export Diagram…

Additional Tips额外提示

  • Update Diagram:

    • If you make changes to your code, you might want to refresh the diagram. You can do this by right-clicking on the diagram and selecting Refresh Diagram.如果您对代码进行更改,您可能需要刷新图表。您可以通过右键单击图表并选择 Refresh Diagram 来完成此操作。
  • Navigating the Diagram:

    • Double-click on any class in the diagram to navigate to its definition in the code.双击图中的任何类以导航到其在代码中的定义。

Example

Suppose you have the following Python classes:假设您有以下 Python 类:

python"># file: person.py
class Person:def __init__(self, name, address, phone):self.name = nameself.address = addressself.phone = phonedef get_details(self):return f"{self.name}, {self.address}, {self.phone}"# file: teacher.py
from person import Personclass Teacher(Person):def __init__(self, name, address, phone, subject):super().__init__(name, address, phone)self.subject = subjectdef teach(self):return f"Teaching {self.subject}"# file: student.py
from person import Personclass Student(Person):def __init__(self, name, address, phone, student_id, major):super().__init__(name, address, phone)self.student_id = student_idself.major = majordef study(self):return f"Studying {self.major}"

Viewing the Class Diagram查看类图

  1. Right-click on the person.py, teacher.py, or student.py file in the Project tool window.右键单击项目工具窗口中的 person.pyteacher.pystudent.py 文件。
  2. Select Diagrams > Show Diagram….
  3. The diagram should display the Person, Teacher, and Student classes along with their relationships.该图应显示 PersonTeacherStudent 类及其关系。

Note笔记

  • The UML class diagram feature is available in the Professional edition of PyCharm. If you are using the Community edition, this feature is not available, and you may need to use a third-party tool or plugin.PyCharm 专业版中提供了 UML 类图功能。如果您使用的是社区版,则此功能不可用,您可能需要使用第三方工具或插件。

By following these steps, you can effectively visualize the structure of your Python code using UML class diagrams in PyCharm, making it easier to understand and manage complex projects.通过执行这些步骤,您可以使用 PyCharm 中的 UML 类图有效地可视化 Python 代码的结构,从而更轻松地理解和管理复杂的项目。

4. Pycharm 中显示类图

If the Diagrams > Show Diagram… option is not available in your PyCharm, it’s likely due to one of the following reasons:如果 Diagrams > Show Diagram… 选项在您的 PyCharm 中不可用,可能是由于以下原因之一造成的:

  1. Edition Limitations: The UML class diagram feature is only available in the Professional edition of PyCharm. If you are using the Community edition, you won’t have this feature.版本限制:UML 类图功能仅在 PyCharm 专业版中可用。如果您使用的是社区版,则不会有此功能。

  2. Configuration Issues: The feature might not be enabled or configured properly in your PyCharm settings.配置问题:您的 PyCharm 设置中可能未启用或正确配置该功能。

Verify Your PyCharm Edition

First, make sure you are using the Professional edition of PyCharm:首先,确保您使用的是 PyCharm 专业版:

  • Go to Help > About (on Windows/Linux) or PyCharm > About (on macOS).转至 Help > About (在 Windows/Linux 上)或 PyCharm > About (在 macOS 上)。
  • Check the edition and version information.检查版本和版本信息。

Install or Enable the UML Plugin安装或启用 UML 插件

If you are using the Professional edition and still can’t find the option, ensure that the UML Support plugin is installed and enabled:如果您使用的是专业版但仍然找不到该选项,请确保已安装并启用 UML 支持插件:

  1. Open Settings/Preferences:打开设置/首选项:

    • Go to File > Settings (on Windows/Linux) or PyCharm > Preferences (on macOS).转至 File > Settings (在 Windows/Linux 上)或 PyCharm > Preferences (在 macOS 上)。
  2. Navigate to Plugins:

    • In the Settings/Preferences dialog, select Plugins.在“设置/首选项”对话框中,选择 Plugins
  3. Search for UML:搜索 UML:

    • In the Plugins page, search for “UML”.在插件页面中,搜索“UML”。
    • If the UML Support plugin is not installed, install it.如果未安装 UML 支持插件,请安装它。
    • If the plugin is installed but disabled, enable it.如果插件已安装但被禁用,请启用它。
  4. Restart PyCharm:

    • Restart PyCharm to apply the changes.重新启动 PyCharm 以应用更改。

Using Third-Party Plugins or Tools使用第三方插件或工具

If you are using the Community edition or prefer another tool, you can use third-party plugins or standalone UML tools to create class diagrams from your Python code. Here are some alternatives:如果您使用的是社区版或更喜欢其他工具,则可以使用第三方插件或独立的 UML 工具从 Python 代码创建类图。以下是一些替代方案:

1. PlantUML Integration

PlantUML is a popular tool for creating UML diagrams, and it has a plugin for PyCharm.PlantUML 是创建 UML 图的流行工具,它有一个 PyCharm 插件。

Install PlantUML Integration Plugin:

  1. Open Settings/Preferences:打开设置/首选项:

    • Go to File > Settings (on Windows/Linux) or PyCharm > Preferences (on macOS).转至 File > Settings (在 Windows/Linux 上)或 PyCharm > Preferences (在 macOS 上)。
  2. Navigate to Plugins:

    • In the Settings/Preferences dialog, select Plugins.在“设置/首选项”对话框中,选择 Plugins
  3. Search for PlantUML Integration:搜索 PlantUML 集成:

    • In the Plugins page, search for “PlantUML Integration”.在插件页面中,搜索“PlantUML Integration”。
    • Install the plugin.
  4. Restart PyCharm:

    • Restart PyCharm to apply the changes.重新启动 PyCharm 以应用更改。
  5. Use PlantUML:

    • Create a new .puml file and write PlantUML code to define your class diagram.创建一个新的 .puml 文件并编写 PlantUML 代码来定义类图。

Example PlantUML code for your Python classes:Python 类的 PlantUML 代码示例:

@startuml
class Person {- name: String- address: String- phone: String+ get_details(): String
}class Teacher {- subject: String+ teach(): String
}class Student {- student_id: String- major: String+ study(): String
}Person <|-- Teacher
Person <|-- Student
@enduml

You can then visualize the diagram within PyCharm using the PlantUML plugin.然后,您可以使用 PlantUML 插件在 PyCharm 中可视化该图。

2. Standalone UML Tools

If you prefer a standalone tool, here are some options:如果您更喜欢独立工具,可以选择以下一些选项:

  • Astah: A professional UML modeling tool.
  • StarUML: An open-source UML tool.
  • Lucidchart: An online diagram tool with UML support.Lucidchart:一个支持 UML 的在线图表工具。
  • Draw.io: An online and offline diagram tool that supports UML diagrams.Draw.io:支持UML图的在线和离线图表工具。

You can manually create class diagrams in these tools based on your Python code.您可以根据您的 Python 代码在这些工具中手动创建类图。

Conclusion

If the built-in UML support is not available in your PyCharm setup, verifying the edition and ensuring the necessary plugins are installed and enabled is crucial. Alternatively, using third-party plugins like PlantUML or standalone UML tools can help you create and visualize class diagrams effectively.如果您的 PyCharm 设置中不提供内置 UML 支持,则验证版本并确保安装并启用必要的插件至关重要。或者,使用 PlantUML 等第三方插件或独立的 UML 工具可以帮助您有效地创建和可视化类图。

5. 安装Graphviz

The error message you’re seeing indicates that PlantUML requires Graphviz to render the diagrams. Graphviz provides the dot executable that PlantUML uses to generate the visual representation of UML diagrams.您看到的错误消息表明 PlantUML 需要 Graphviz 来呈现图表。 Graphviz 提供了 PlantUML 用于生成 UML 图的可视化表示的 dot 可执行文件。

Steps to Install Graphviz

On Ubuntu/Debian:
  1. Open Terminal.

  2. Install Graphviz:

    sudo apt-get update
    sudo apt-get install graphviz
    
On macOS:
  1. Open Terminal.

  2. Install Homebrew (if you don’t have it installed):安装 Homebrew(如果尚未安装):

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
  3. Install Graphviz:

    brew install graphviz
    
On Windows:
  1. Download the Graphviz installer from the Graphviz download page.从 Graphviz 下载页面下载 Graphviz 安装程序。
  2. Run the installer and follow the instructions to complete the installation.运行安装程序并按照说明完成安装。
  3. Add Graphviz to the system PATH:将 Graphviz 添加到系统路径:
    • Right-click on “This PC” or “Computer” on the desktop or in File Explorer and select “Properties”.右键单击桌面上或文件资源管理器中的“此电脑”或“计算机”,然后选择“属性”。
    • Click “Advanced system settings” on the left.点击左侧的“高级系统设置”。
    • In the System Properties window, click the “Environment Variables…” button.在“系统属性”窗口中,单击“环境变量…”按钮。
    • In the Environment Variables window, find the “Path” variable in the “System variables” section and select it, then click “Edit…”.在“环境变量”窗口中,在“系统变量”部分中找到“Path”变量并选择它,然后单击“编辑…”。
    • Click “New” and add the path to the bin directory of your Graphviz installation (e.g., C:\Program Files (x86)\Graphviz2.38\bin).单击“新建”并添加 Graphviz 安装的 bin 目录的路径(例如 C:\Program Files (x86)\Graphviz2.38\bin )。
    • Click “OK” to close all the windows.

Verify the Installation

After installing Graphviz, verify that it is correctly installed by running the following command in the terminal or command prompt:安装 Graphviz 后,通过在终端或命令提示符中运行以下命令来验证其是否正确安装:

dot -version

You should see output indicating the installed version of Graphviz.您应该看到指示已安装的 Graphviz 版本的输出。

Configure PyCharm to Use Graphviz

  1. Restart PyCharm to ensure it picks up the newly installed Graphviz.
  2. Open your PlantUML file and try to render the diagram again.打开您的 PlantUML 文件并尝试再次渲染该图。

Example Verification in PlantUML FilePlantUML 文件中的验证示例

To verify the setup, you can use the provided PlantUML code in your .puml file:要验证设置,您可以使用 .puml 文件中提供的 PlantUML 代码:

@startuml
class Person {- name: String- address: String- phone: String+ get_details(): String
}class Teacher {- subject: String+ teach(): String
}class Student {- student_id: String- major: String+ study(): String
}Person <|-- Teacher
Person <|-- Student
@enduml

Once Graphviz is installed, PlantUML should be able to render the diagram correctly. If you still encounter issues, ensure that the PATH environment variable is correctly set and PyCharm is restarted to recognize the changes.安装 Graphviz 后,PlantUML 应该能够正确渲染图表。如果仍然遇到问题,请确保正确设置 PATH 环境变量并重新启动 PyCharm 以识别更改。


http://www.ppmy.cn/server/49785.html

相关文章

第十一章:接口

接口 文章目录 接口一、简介1.1 接口是什么1.2 接口的作用1.3 接口的开发与调用1.4 接口的组成 二、RESTful API三、json-server四、接口测试工具五、接口的创建 一、简介 1.1 接口是什么 接口是前后端通信的桥梁 简单理解&#xff1a;一个接口就是 服务中的一个路由规则&am…

数据库第一次实验报告

1. 使用 SQL 语句创建数据库 studentsdb。 2. 使用 SQL 语句选择 studentsdb 为当前使用数据库。 3. 使用 SQL 语句在 studentsdb 数据库创建数据表 student_info、curriculum、grade 4. 使用 SQL 语句 INSERT 向 studentsdb 数据库的 student_info、curriculum、grade 表插…

JAVA8 常用Stram处理方法

JAVA8 常用Stram处理方法 排序排序对象集合属性一升序 属性二降序List转MapList分组求和提取字符串根据属性去重分组排序求和 排序 List<MachineOrderResponse.BackRecord> noSList ss.stream().sorted(Comparator.comparing(MachineOrderResponse.BackRecord::getTime)…

分片表属性的查询

select tabinfo.表名,f.partition 分区名,tabinfo.存储空间,tabinfo.段数量,tabinfo.分配总数,tabinfo.已用数量,tabinfo.行长,tabinfo.行数 from (select a.tabname 表名, c.name 存储空间,b.nextns 段数量,b.nptotal 分配总数,b.npused 已用数量,b.rowsize 行长,b.nrows 行数…

Linux C编译器从零开发三

AST语法树 BNF抽象 expr equality equality relational ("" relational | "!" relational)* relational add ("<" add | "<" add | ">" add | ">" add)* add mul ("" …

Oracle 19C 数据库表被误删除的模拟恢复

Oracle 19C 数据库表被误删除的模拟恢复操作 1、模拟创建表用于恢复测试 sqlplus zzh/zzh SQL> create table obj_tb tablespace users as select * from dba_objects; Table created. SQL> select count(*) from obj_tb; COUNT(*) ---------- 72373 2、记录当前…

SGPT论文阅读笔记

这是篇想要用GPT来提取sentence embedding的工作&#xff0c;提出了两个框架&#xff0c;一个是SGPT-BE&#xff0c;一个是SGPT-CE&#xff0c;分别代表了Bi-Encoder setting和Cross-Encoder setting。CE的意思是在做阅读理解任务时&#xff0c;document和query是一起送进去&am…

AI工具对音乐的影响

AI工具对音乐的影响是深远且多方面的&#xff0c;以下是对其影响的清晰归纳和分点表示&#xff1a; 一、音乐创作方面的影响 音乐生成&#xff1a; AI能够通过深度学习算法分析大量的音乐作品&#xff0c;并生成新的音乐作品。例如&#xff0c;OpenAI的GPT-3模型可以根据输入…