zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    thinkphp分页样式css代码
    thinkphp两表,多表联合查询及分页的连贯操作写法
    ThinkPHP3.2.3新特性之:数据库设置
    ThinkPHP的主从数据库配置
    CentOS7 64位下MySQL5.7安装与配置(YUM)
    sessionid如何产生?由谁产生?保存在哪里?
    GIT使用
    Windows下安装composer
    树莓派debian配置lamp[解决Apache不显示php网页]
    【Linux】Debian 下安装 Apache,MySQL,PHP
  • 原文地址:https://www.cnblogs.com/dylancao/p/11458686.html
Copyright © 2011-2022 走看看