python各层级目录下import方法代码实例

yipeiwu_com5年前Python基础

这篇文章主要介绍了python各层级目录下import方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

以前经常使用python2.现在很多东西都切换到了python3,发现很多东西还是存在一些差异化的。跨目录import是常用的一种方法,并且有不同的表现形式,新手很容易搞混。有必要这里做个总结,给大家科普一下:

1 同级目录下的调用:

同级目录下的调用比较简单,一般使用场景是不同类的相互调用。不用考虑路径问题,常用的格式是:from file import * 或者 from file import class/function 等。

下面以一个例子作为说明:

程序结构:

➜ dir_test git:(master) ✗ tree
.
├── pycache
│  └── test1.cpython-37.pyc
├── dir1
│  └── test3.py
├── test1.py
└── test2.py

代码:

from test1 import *
# the below is also ok
#from test1 import dir_test

def test_file2():
  print("this is test file2")

dir_test()
test_file2()

2 子目录下的调用:

子目录下的函数调用,正常的情况下,需要包含子目录的,常用的格式如下:form dir1.file import * 或者: from dir1 import file等。

下面以一个例子说明:

➜ dir_test git:(master) ✗ tree
.
├── pycache
│  └── test1.cpython-37.pyc
├── dir1
│  ├── pycache
│  │  └── test3.cpython-37.pyc
│  └── test3.py
├── test1.py
└── test2.py

代码:

from test1 import *
# the below is also ok
#from test1 import dir_test

from dir1.test3 import *

def test_file2():
  print("this is test file2")

dir_test()
dir1_test()

3 上级目录下的调用:

上级目录调用要比上两种复杂,这里要用到sys函数,首先要在将要调用的文件下面建一个空文件:init.py 然后在调用这个文件的文件里面添加:sys.path.append("…"),才可以调用成功:

下面是一个例子:文件结构:

➜ dir_test git:(master) ✗ tree
.
├── pycache
│  └── test1.cpython-37.pyc
├── dir1
│  ├── init.py
│  ├── pycache
│  │  ├── init.cpython-37.pyc
│  │  └── test3.cpython-37.pyc
│  └── test3.py
├── dir2
│  └── test4.py
├── test1.py
└── test2.py

代码:

#!python3

import sys
sys.path.append("..")
from dir1.test3 import *
#import dir1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pytorch下大型数据集(大型图片)的导入方式

使用torch.utils.data.Dataset类 处理图片数据时, 1. 我们需要定义三个基本的函数,以下是基本流程 class our_datasets(Data.Datas...

教女朋友学Python(一)运行环境搭建 原创

教女朋友学Python(一)运行环境搭建 原创

下班比较早,吃了饭没什么事,就和女朋友一起研究了Python。 编程语言有很多,为什么选择它呢?因为它火吧,没什么好解释的,下面开始第一步,环境搭建。网上的教程实在太多,各种系统的各种版...

Python实现的特征提取操作示例

本文实例讲述了Python实现的特征提取操作。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- """ Created on Mon Aug 21 1...

python http接口自动化脚本详解

python http接口自动化脚本详解

今天给大家分享一个简单的python脚本,使用python进行http的接口测试,脚本很简单,逻辑是:读取excel写好的测试用例,然后根据excel中的用例内容进行调用,判断预期结果中...

Python 数据可视化pyecharts的使用详解

Python 数据可视化pyecharts的使用详解

什么是pyecharts?   pyecharts 是一个用于生成 Echarts 图表的类库。 echarts是百度开源的一个数据可视化 JS 库,主要用于数据可视化。pyechart...