简体   繁体   English

当我尝试调用我的函数时,为什么会出现 NameError?

[英]Why am I getting a NameError when I try to call my function?

This is my code:这是我的代码:

import os

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_AI\memories')

When I execute this, it throws an error:当我执行这个时,它会抛出一个错误:

File "foo.py", line 6, in <module>
    createDirs()
NameError: name 'createDirs' is not defined

I made sure it's not a typo and I didn't misspell the function's name, so why am I getting a NameError?我确定这不是拼写错误,也没有拼错函数的名称,那么为什么会出现 NameError?

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.def createDirs():块移动到文件顶部,在导入下方。

Some languages allow you to use functions before defining them.某些语言允许您在定义函数之前使用它们。 For example, javascript calls this "hoisting".例如,javascript 将此称为“提升”。 But Python is not one of those languages.但是 Python 不是这些语言之一。


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_AI\memories')

doStuff()

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.即使在第 7 行调用了createDirs()并且在第 9 行定义了它,但这不是问题,因为def createDirsdoStuff()在第 12 行执行之前执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM