zoukankan      html  css  js  c++  java
  • [语言基础] 模块、包遇到的问题

    准备:目录结构与说明

    top
    │  main.py
    │  
    ├─father1
    │      module1.py
    │      module1_1.py
    │      __init__.py
    │      
    └─father2
        │  module2.py
        │  __init__.py
        │  
        └─son2
                module2_son2.py
                __init__.py
    #module1.py 
    name = 'father1'
    
    #module1_1.py
    age = '12'
    
    #module2.py
    name = 'father2'

    #module2_son2.py name = 'son2'

    模块导入

    #从 文件夹father1中 导入 模块module1
    from father1 import module1
    print(module1.name)  #father1

    包导入

    '''
    import 风格
    缺点:使用的时候需要再重复一遍import的内容
    '''
    import father1.module1
    print(father1.module1.name) #father1
    
    
    
    '''
    from xxx import xxx 风格
    '''
    #从 文件夹father1 -> 模块module1 中导入 变量name
    from father1.module1 import name
    print(name)  #father1
    
    #从father2son2文件夹中导入模块module2_son2
    from father2.son2 import module2_son2
    print(module2_son2.name)  #son2

    问题1:可不可以直接import father1呢?

    ->不行,不能直接import文件夹,import的必须是模块或者变量

    问题2:那么我想import father1,怎么办呢?

    top
    │  main.py
    │  
    ├─father1
    │      module1.pymodule1_1.py
    │      __init__.py
    │      
    └─ 略...
    # father1 -> __init__.py
    from . import module1,module1_1
    
    # main.py
    import father1
    print(father1.module1.name)

    问题3:在module1.py中相对导入同目录的模块module1_1,然后运行module1.py,结果报错: cannot import name 'module1_1' from '__main__' (.module1.py) ,如何解决?

    top
    │  main.py
    │  
    ├─father1
    │      module1.py
    │      module1_1.py
    │      __init__.py
    │      
    └─ 略...
    # module1.py
    from . import module1_1
    '''
    运行module1.py:
    ..略..	opfather1> python .module1.py
    Traceback (most recent call last):
      File ".module1.py", line 1, in <module>
        from . import module1_1
    ImportError: cannot import name 'module1_1' from '__main__' (.module1.py)
    '''

     答:运行顶层文件模块 -> main.py

    # main.py
    from father1 import module1
    print(module1.module1_1.age)

    原因:参考Python学习手册p583

    相对导入适用于只在包内导入。这种功能的模块搜索路径修改只应用于位于包内的模块文件中的import语句。位于包文件之外的通常的导入将像前面所介绍的那样工作,首先自动搜索包含了顶级脚本的目录。

  • 相关阅读:
    关于生成并发唯一性流水号的解决方案
    父页面得到<iframe>
    struts2 convention配置中常见配置选项及说明
    Struts2下关于Calendar,date的一些处理
    怎样将用户名和密码保存到Cookie中?【转】
    如何调用用户控件(UserControl)的方法 .
    Struts遍历标签<s:iterator>总结 .
    在事业的开展上保持归零的心态
    这种日子最轻松,这样的人生最快乐
    诚实是人世间最珍贵的宝物,是每个人都应当坚守的伟大情操
  • 原文地址:https://www.cnblogs.com/remly/p/11581991.html
Copyright © 2011-2022 走看看