python做一个分层,分为一级部门二级部门三级部门
时间: 2023-07-25 12:20:26 浏览: 98
好的,以下是一个三级部门的示例代码:
```python
class Department:
def __init__(self, name):
self.name = name
self.sub_departments = []
def add_sub_department(self, sub_department):
self.sub_departments.append(sub_department)
def print_structure(self, level=0):
print("| " * level + "|--", self.name)
for sub_department in self.sub_departments:
sub_department.print_structure(level+1)
```
这个示例中,我们定义了一个 `Department` 类,表示部门。每个部门有一个 `name` 属性,并且可以包含多个子部门,子部门通过 `add_sub_department` 方法添加到父部门中。最后,我们定义了一个 `print_structure` 方法,用于打印出整个部门的层级结构。
使用示例:
```python
# 创建部门
head_department = Department("总公司")
sub_department1 = Department("一级部门1")
sub_department2 = Department("一级部门2")
sub_department3 = Department("一级部门3")
sub_sub_department1 = Department("二级部门1")
sub_sub_department2 = Department("二级部门2")
sub_sub_department3 = Department("二级部门3")
sub_sub_sub_department1 = Department("三级部门1")
sub_sub_sub_department2 = Department("三级部门2")
# 添加子部门
sub_department1.add_sub_department(sub_sub_department1)
sub_department1.add_sub_department(sub_sub_department2)
sub_department2.add_sub_department(sub_sub_department3)
sub_sub_department1.add_sub_department(sub_sub_sub_department1)
sub_sub_department2.add_sub_department(sub_sub_sub_department2)
head_department.add_sub_department(sub_department1)
head_department.add_sub_department(sub_department2)
head_department.add_sub_department(sub_department3)
# 打印层级结构
head_department.print_structure()
```
输出结果:
```
|-- 总公司
| |-- 一级部门1
| | |-- 二级部门1
| | | |-- 三级部门1
| | |-- 二级部门2
| | | |-- 三级部门2
| |-- 一级部门2
| | |-- 二级部门3
| |-- 一级部门3
```
这样就可以方便地打印出整个部门的层级结构了。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)