学习记录:python 调用模块,自定义模块,跨目录调用文件

模块

# 调用模组 ctime()函数用于获取当前时间
# import time
# print(time.ctime())

# 直接导入time模块下的多个函数
# from time import time, sleep

# 导入time模块下的所有函数
# from time import *
# print(ctime())
# print('休眠一秒')
# sleep(1)
# print(ctime())

# 如果导入的函数刚好与自己定义的函数重名,那么可以用 "as" 对导入的函数重命名
# 对导入的sleep 函数重命名
# from time import sleep as sys_sleep

# def sleep(sec):
#     print('hello')

自定义模块

# 创建一个目录 test/ ,并在目下创建两文件,结构如下:
# test/
#  |__test1.py
#  |__test2.py

# 在test1.py 创建add() 函数
# 创建add 函数
# def add(a, b):
#     return a + b

# 在test2.py 引入test1 的 add函数
# 导入 test1 文件中的add 函数
# from test1 import add
# print(1, 1)

跨目录调用文件

# 文件结构如下:
# test1/
#  |__test11/
#  |  |__test111.py
#  | 
#  |__test22/
#     |__test222.py

# 查找工作目录
# import sys
# print(sys.path)

# 跨文件调用test1 的 add函数
# import sys
# sys.path.append('D:\\demo\\test1\\test11')
# from test1 import add
# print(add(2,3))

# 优化代码
# import sys
# from os.path import dirname, abspath
# path1 = dirname(dirname(abspath(__file__)))
# sys.path.append(path1 + '\\test11')
# from test1 import add
# print(add(2,3))

猜你喜欢

转载自blog.csdn.net/qq_26086231/article/details/114240731
今日推荐