Python(12)——Python高级特性之模块和包


前言

1、python中的模块

  • python模块实质上是一个python文件
  • 自定义的python文件的文件名一定不要和已有的模块冲突
  • 导入模块实质上是加载并执行模块的内容

1.1 导入模块的几种方式

  • 方式一
hello.py
digits='0123'
import hello
print(hello.digits)
输出:
0123
  • 方式二
hello.py ## 模块文件
digits='0123'

def info():
    print('打印信息')

import hello
print(hello.digits)
hello.info()
输出:
0123
打印信息

  • 方式三
from hello import info
info()
输出:
打印信息

  • 方式四
from hello import info as f
f()
输出:
打印信息

  • 方式五
from hello import *
print(digits)
输出:
0123

1.2 模块的其他信息

import sys
print(sys.path)  ## 模块的查询路径
import hello
print(dir(hello)) ## 查看hello模块可以使用的变量和函数
print(hello.__doc__)  ## 查看模块的说明文档
print(hello.__file__)  ## 显示模块的绝对路径
print(hello.__name__) ## __name__当模块被导入时,显示的是模块的名称。

在这里插入图片描述

1.3 name的特殊用法

hello.py文件: 当在模块内部执行__name__的值为__main__;当模块被导入时,__name__的值为hello(模块名)

digits='0123'

def info():
    print('打印信息')
if __name__ == '__main__':
    print(__name__)

当模块内部执行时,需要执行的代码。 当模块被导入,则不执行。

import hello
print(hello.digits)
hello.info()
print(hello.__name__)
输出:
0123
打印信息
hello

2、包的管理

  1. 包实质上是包含__init__.py文件的目录。
  2. 导入包实质是 执行包里面的__init__.py的内容init.py文件
print('正在加载__init__')
import sdk
输出:正在加载__init__

导入包的方式

创建python包sdk,创建两个子文件age.py和name.py

age.py
def create():
    print('name添加成功')
    name.py
def create():
    print('age添加成功')

  • 方式一
from sdk import age
from sdk import name
age.create()
name.create()
输出:
age创建成功
name添加成功

  • 方式二

需要在包的__init__.py添加导入信息

from . import name
from . import age
import sdk
sdk.name.create()
sdk.age.create()
输出:
name添加成功
age创建成功
本篇文章到此结束

猜你喜欢

转载自blog.csdn.net/weixin_41191813/article/details/113882751