且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么当我尝试调用我的函数时会收到 NameError?

更新时间:2023-12-03 11:00:22

除非已经定义了函数,否则不能调用它.将 def createDirs(): 块移动到文件顶部,在导入下方.

You can't call a function unless you've already defined it. Move the def createDirs(): block up to the top of your file, below the imports.

有些语言允许您在定义函数之前使用它们.例如,javascript 将此称为提升".但 Python 不是这些语言之一.

Some languages allow you to use functions before defining them. For example, javascript calls this "hoisting". But Python is not one of those languages.

请注意,在比创建函数的行高的行中引用函数是允许的,只要按时间顺序定义出现在使用之前.例如,这是可以接受的:

Note that it's allowable to refer to a function in a line higher than the line that creates the function, as long as chronologically the definition occurs before the usage. For example this would be acceptable:

import os

def doStuff():
    if os.path.exists(r'C:Genisis_AI'):
        print("Main File path exists! Continuing with startup")
    else:
        createDirs()

def createDirs():
    os.makedirs(r'C:Genisis_AImemories')

doStuff()

即使 createDirs() 在第 7 行调用并在第 9 行定义,这也不是问题,因为 def createDirsdoStuff() 在第 12 行.

Even though createDirs() is called on line 7 and it's defined on line 9, this isn't a problem because def createDirs executes before doStuff() does on line 12.