【问题标题】:How to import module that contains a file in it如何导入包含文件的模块
【发布时间】:2012-08-27 09:51:53
【问题描述】:

我安装了一个我自己创建的用于学习的自定义模块。如果我这样做了

from my_first_module import test
test.thisprintssomething()

该功能会起作用,但如果我这样做了

import my_first_module
test.thisprintssomething()

Python 吐出,NameError: name 'test' is not defined。不使用“from”如何导入?

编辑:

我自己修好了。我忘记在 my_first_module 模块中的 init.py 中添加“导入测试”行。

【问题讨论】:

    标签: python module


    【解决方案1】:

    因为你正在导入my_first_module 你要告诉代码,test属于my_first_module

    import my_first_module
    
    my_first_module.test.thisprintssomething()
    

    如需更多说明,您可以查看Importing Python Modules

    【讨论】:

    • 当我尝试这样做时,我收到此错误“AttributeError: 'module' object has no attribute 'test'。
    【解决方案2】:
    import my_first_module
    
    my_first_module.test.thisprintssomething()
    

    这会奏效。阅读更多http://docs.python.org/tutorial/modules.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多