代码之家  ›  专栏  ›  技术社区  ›  Joonatan

在python/jupyter上导入模块

  •  0
  • Joonatan  · 技术社区  · 3 年前

    我做了一个非常简单的测试。py-文件,我想将其用作模块:

    def add(a,b):
        return a+b
    
    def mult(a,b):
        return a*b
    

    当我运行另一个笔记本并尝试导入它时,导入是“成功的”。

    import numpy as np
    import test 
    
    x= int(input("enter value x"))
    y= int(input("enter value x"))
    
    array1= np.array([x,y])
    array2= np.array([-x,-y])  
    
    answer1 = add(x,y)
    answer2 = mult(x,y)
    
    print(answer1, answer2)
    

    但是,当我运行代码时,它会返回:

    "NameError: name 'add' is not defined"
    

    我可以通过编辑我的代码来绕过它:

    from test import add, mult
    

    然后它就会起作用。

    我不太明白为什么我不能运行整个文件?有人能启发我吗?

    因为有这样的功能:

    if __name__ == '__main__':
    

    用于不从模块返回结果的?对我来说,当我不能将整个文件作为导入运行时,这就没有意义了?

    我知道这个问题有点模糊,但我很感谢你抽出时间

    1 回复  |  直到 3 年前
        1
  •  0
  •   iamakhilverma    3 年前

    如果你想用 import test 得到你想要的,然后你想写:

    answer1 = test.add(x,y)
    answer2 = test.mult(x,y)
    

    它会起作用的。这是因为您刚刚将模块导入到当前名称空间中,需要使用该模块的名称后跟 . ,即。, test. 就你而言。你用过吗 from test import add, mult ,这意味着您将不会导入模块测试,而是导入函数 add, mult 并可以直接访问它们。