Python包模块化调用方式详解

                           作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

  一般来说,编程语言中,库、包、模块是同一种概念,是代码组织方式。 Python中只有一种模块对象类型,但是为了模块化组织模块的便利,提供了"包"的概念。

  模块module,指的是Python的源代码文件。 包package,指的是模块组织在一起的和包名同名的目录及其相关文件。 

 

一.导入语句

 1 #!/usr/bin/env python
 2 #_*_conding:utf-8_*_
 3 #@author :yinzhengjie
 4 #blog:http://www.cnblogs.com/yinzhengjie
 5 
 6 import os
 7 import pathlib  as p1      #倒入模块使用别名
 8 from os.path import exists          #加载、初始化os、os.path模块,exists加入本地名词空间并绑定
 9 
10 """
11 总结
12     找到from子句中指定的模块,加载并初始化它(注意不是导入)
13  
14     对于import子句后的名称
15         1>.先查from子句导入的模块是否具有该名称的属性
16         2>.如果不是,则尝试导入该名称的子模块
17         3>.还没有找到,则抛出ImportError异常
18         4>.这个名称保存到本地名词空间中,如果有as子句,则使用as子句后的名称
19 """
20 
21 if exists('o:/t'):
22     print('Found')
23 else:
24     print('Not Found')
25 print(dir())
26 print(exists)
27 
28 # 4种方式获得同一个对象exist
29 print(os.path.exists)
30 print(exists)
31 print(os.path.__dict__['exists']) # 字符串
32 print(getattr(os.path, 'exists')) # 字符串
33 
34 
35 print(p1)
36 print(p1.Path,id(p1.Path))
37 print(dir())
Not Found
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'exists', 'os', 'p1']
<function exists at 0x1006f9d08>
<function exists at 0x1006f9d08>
<function exists at 0x1006f9d08>
<function exists at 0x1006f9d08>
<function exists at 0x1006f9d08>
<module 'pathlib' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pathlib.py'>
<class 'pathlib.Path'> 4328656856
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'exists', 'os', 'p1']
以上代码执行结果戳这里

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-30
  • 2022-01-08
猜你喜欢
  • 2021-08-14
  • 2021-12-18
  • 2023-03-20
  • 2021-09-10
  • 2022-12-23
  • 2021-11-09
相关资源
相似解决方案