Python - 'module' 调用函数时返回的对象不可调用

Python - 'module' object is not callable returned when calling function

我是 Python 的新手,刚开始学习它,但 运行 我的功能遇到了问题。我有一点 Matlab 的背景,所以这可能是我的一些困惑的来源。

这是我在我的电脑上使用 Notepad++ 用脚本编写的代码:

def print_order_numbers(amount):

    i = 0
    numbers = []

    while i < amount:
        print("At the top i is %d" %i)
        numbers.append(i)

        i = i + 1
        print ("Numbers now: ", numbers)
        print("at the bottom i si %d" %i)

    print ("the numbers: ")

    for num in numbers:
        print (num)

然后在 python 中加载函数后使用:

from filename import print_order_numbers

但是,因为函数本身没有 return 任何东西,也没有给定参数,所以这不会做任何事情。所以当我尝试调用函数时,像这样:

print_order_numbers(2)

它给了我错误回溯: 文件“”,第 1 行,位于 NameError:名称 'print_order_numbers' 未定义

我发现如果我将此调用与编写函数的脚本放在同一个脚本中,当我导入函数时,它会正确运行。为什么我的函数被 Python 识别为模块,为什么在脚本中调用该函数有效?

有什么方法可以直接调用python命令window中的函数,而不必将调用放在函数所在的脚本中? Matlab 的函数允许您执行此操作,如果我想从另一个脚本调用函数,它会使事情变得容易得多。 (或者我是否只需要在与调用它的其余代码相同的脚本中使用该函数?)

抱歉,如果这是一个基本问题,我只是想更好地理解这个主题,并且无法在我浏览过的所有 questions/tutorials 中找到直接的答案。提前致谢!

你的文件名是print_order_numbers.py吗?如果是这样,您需要更改名称。解释器认为您指的是模块而不是函数。

如果不行,你可以试试


import filename
filename.print_order_numbers(2)

否则,您需要提供其他人所说的更多上下文。