我有一个函数,我正在制作另一个需要调用第一个函数的函数。我没有 Python 方面的经验,但我知道在像 MATLAB 这样的语言中,只要它们在同一目录中就可以了。
一个基本的例子:
def square(x):
square = x * x
Run Code Online (Sandbox Code Playgroud)
(并保存)
现在在我的新函数中,我想使用我尝试过的函数 square:
def something (y, z)
import square
something = square(y) + square(z)
return something
Run Code Online (Sandbox Code Playgroud)
其中显示:builtins.TypeError: 'module' object is not callable。
我该怎么办?
import如果它在同一个文件中,则不需要。
只需square从something函数中调用。
def square(x):
square = x * x
return square
def something (y, z)
something = square(y) + square(z)
return something
Run Code Online (Sandbox Code Playgroud)
更简单:
def square(x):
return x * x
def something (y, z)
return square(y) + square(z)
Run Code Online (Sandbox Code Playgroud)
如果且仅当您square在square模块中定义了该函数,那么您应该改为从中导入简单名称。
from square import square
Run Code Online (Sandbox Code Playgroud)
如果您不想更改任何内容,则需要使用其完全限定名称:
something = square.square(y) + square.square(z)
Run Code Online (Sandbox Code Playgroud)
模块的名称是square,并且您不能调用模块上的函数。