1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+ """
4+ 包的基本概念和结构
5+
6+ 包(Package)是一种组织Python模块的方式,它是一个包含多个模块的目录。
7+ 包的主要作用是避免模块名冲突,并提供更好的代码组织结构。
8+
9+ 学习要点:
10+ 1. 包的定义和作用
11+ 2. 包的目录结构
12+ 3. __init__.py文件的重要性
13+ 4. 包与模块的区别
14+ """
15+
16+ import os
17+ import sys
18+
19+ def demonstrate_package_concept ():
20+ """
21+ 演示包的基本概念
22+ """
23+ print ("=== 包的基本概念 ===" )
24+ print ("\n 1. 什么是包?" )
25+ print (" - 包是一个包含多个模块的目录" )
26+ print (" - 包必须包含一个__init__.py文件(可以为空)" )
27+ print (" - 包可以包含子包,形成层次结构" )
28+
29+ print ("\n 2. 包的作用:" )
30+ print (" - 避免模块名冲突" )
31+ print (" - 提供更好的代码组织结构" )
32+ print (" - 支持分层的模块命名空间" )
33+
34+ print ("\n 3. 包与模块的区别:" )
35+ print (" - 模块:单个.py文件" )
36+ print (" - 包:包含__init__.py的目录,可包含多个模块" )
37+
38+ def show_package_structure ():
39+ """
40+ 展示典型的包结构
41+ """
42+ print ("\n === 典型的包结构 ===" )
43+ structure = """
44+ mypackage/ # 包目录
45+ ├── __init__.py # 包初始化文件(必需)
46+ ├── module1.py # 模块1
47+ ├── module2.py # 模块2
48+ ├── subpackage/ # 子包
49+ │ ├── __init__.py # 子包初始化文件
50+ │ ├── submodule1.py # 子模块1
51+ │ └── submodule2.py # 子模块2
52+ └── utils/ # 工具包
53+ ├── __init__.py # 工具包初始化文件
54+ ├── helpers.py # 辅助函数
55+ └── constants.py # 常量定义
56+ """
57+ print (structure )
58+
59+ def create_example_package ():
60+ """
61+ 创建一个示例包结构
62+ """
63+ print ("\n === 创建示例包结构 ===" )
64+
65+ # 定义包结构
66+ package_structure = {
67+ 'example_package' : {
68+ '__init__.py' : '# 这是example_package包的初始化文件\n print("正在导入example_package包")' ,
69+ 'math_utils.py' : '''
70+ # 数学工具模块
71+ def add(a, b):
72+ """加法函数"""
73+ return a + b
74+
75+ def multiply(a, b):
76+ """乘法函数"""
77+ return a * b
78+
79+ def factorial(n):
80+ """计算阶乘"""
81+ if n <= 1:
82+ return 1
83+ return n * factorial(n - 1)
84+ ''' ,
85+ 'string_utils.py' : '''
86+ # 字符串工具模块
87+ def reverse_string(s):
88+ """反转字符串"""
89+ return s[::-1]
90+
91+ def capitalize_words(s):
92+ """首字母大写"""
93+ return ' '.join(word.capitalize() for word in s.split())
94+
95+ def count_words(s):
96+ """统计单词数量"""
97+ return len(s.split())
98+ '''
99+ }
100+ }
101+
102+ # 创建包目录和文件
103+ base_path = os .path .dirname (__file__ )
104+
105+ for package_name , files in package_structure .items ():
106+ package_path = os .path .join (base_path , package_name )
107+
108+ # 创建包目录
109+ if not os .path .exists (package_path ):
110+ os .makedirs (package_path )
111+ print (f"创建包目录: { package_path } " )
112+
113+ # 创建文件
114+ for filename , content in files .items ():
115+ file_path = os .path .join (package_path , filename )
116+ with open (file_path , 'w' , encoding = 'utf-8' ) as f :
117+ f .write (content )
118+ print (f"创建文件: { file_path } " )
119+
120+ print ("\n 示例包结构创建完成!" )
121+ return os .path .join (base_path , 'example_package' )
122+
123+ def demonstrate_package_import (package_path ):
124+ """
125+ 演示包的导入
126+ """
127+ print ("\n === 包的导入演示 ===" )
128+
129+ # 将包路径添加到sys.path
130+ parent_path = os .path .dirname (package_path )
131+ if parent_path not in sys .path :
132+ sys .path .insert (0 , parent_path )
133+
134+ try :
135+ # 导入整个包
136+ print ("\n 1. 导入整个包:" )
137+ print (" import example_package" )
138+ import example_package
139+
140+ # 导入包中的模块
141+ print ("\n 2. 导入包中的模块:" )
142+ print (" from example_package import math_utils" )
143+ from example_package import math_utils
144+
145+ # 使用导入的模块
146+ print ("\n 3. 使用导入的模块:" )
147+ result1 = math_utils .add (5 , 3 )
148+ result2 = math_utils .multiply (4 , 6 )
149+ result3 = math_utils .factorial (5 )
150+
151+ print (f" math_utils.add(5, 3) = { result1 } " )
152+ print (f" math_utils.multiply(4, 6) = { result2 } " )
153+ print (f" math_utils.factorial(5) = { result3 } " )
154+
155+ # 导入特定函数
156+ print ("\n 4. 导入特定函数:" )
157+ print (" from example_package.string_utils import reverse_string, capitalize_words" )
158+ from example_package .string_utils import reverse_string , capitalize_words
159+
160+ text = "hello world python"
161+ reversed_text = reverse_string (text )
162+ capitalized_text = capitalize_words (text )
163+
164+ print (f" 原文本: '{ text } '" )
165+ print (f" 反转后: '{ reversed_text } '" )
166+ print (f" 首字母大写: '{ capitalized_text } '" )
167+
168+ except ImportError as e :
169+ print (f"导入错误: { e } " )
170+ except Exception as e :
171+ print (f"其他错误: { e } " )
172+
173+ def show_package_attributes ():
174+ """
175+ 展示包的属性
176+ """
177+ print ("\n === 包的属性 ===" )
178+
179+ try :
180+ import example_package
181+
182+ print ("\n 包的常用属性:" )
183+ print (f" __name__: { example_package .__name__ } " )
184+ print (f" __file__: { getattr (example_package , '__file__' , 'N/A' )} " )
185+ print (f" __path__: { getattr (example_package , '__path__' , 'N/A' )} " )
186+ print (f" __package__: { getattr (example_package , '__package__' , 'N/A' )} " )
187+
188+ # 显示包中的内容
189+ print ("\n 包中的内容:" )
190+ for attr in dir (example_package ):
191+ if not attr .startswith ('_' ):
192+ print (f" { attr } " )
193+
194+ except ImportError :
195+ print ("请先运行create_example_package()创建示例包" )
196+
197+ def cleanup_example_package ():
198+ """
199+ 清理示例包(可选)
200+ """
201+ import shutil
202+
203+ base_path = os .path .dirname (__file__ )
204+ package_path = os .path .join (base_path , 'example_package' )
205+
206+ if os .path .exists (package_path ):
207+ try :
208+ shutil .rmtree (package_path )
209+ print (f"\n 已清理示例包: { package_path } " )
210+ except Exception as e :
211+ print (f"清理失败: { e } " )
212+ else :
213+ print ("\n 示例包不存在,无需清理" )
214+
215+ def main ():
216+ """
217+ 主函数:演示包的基本概念
218+ """
219+ print ("Python包的基本概念和结构" )
220+ print ("=" * 50 )
221+
222+ # 1. 演示包的基本概念
223+ demonstrate_package_concept ()
224+
225+ # 2. 展示包结构
226+ show_package_structure ()
227+
228+ # 3. 创建示例包
229+ package_path = create_example_package ()
230+
231+ # 4. 演示包的导入
232+ demonstrate_package_import (package_path )
233+
234+ # 5. 展示包的属性
235+ show_package_attributes ()
236+
237+ print ("\n === 学习小结 ===" )
238+ print ("1. 包是包含__init__.py文件的目录" )
239+ print ("2. 包可以包含多个模块和子包" )
240+ print ("3. 包提供了命名空间,避免模块名冲突" )
241+ print ("4. 可以通过import语句导入包和包中的模块" )
242+ print ("5. 包有自己的属性,如__name__, __file__, __path__等" )
243+
244+ # 询问是否清理示例包
245+ print ("\n 注意:示例包已创建在当前目录下" )
246+ print ("如需清理,请调用cleanup_example_package()函数" )
247+
248+ if __name__ == "__main__" :
249+ main ()
0 commit comments