Python:NameError:未定义全局名称“foobar”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4068785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:06:26  来源:igfitidea点击:

Python: NameError: global name 'foobar' is not defined

pythonnamespacesnameerror

提问by skyeagle

I have written the following class:

我编写了以下课程:

class myClass(object):
    def __init__(self):
        pass

    def foo(self, arg1, arg2):
        pp = foobar(self, arg1, arg2)
        if pp:
            return 42
        else
            return -666


    def foobar(self, arg1, arg2):
        if arg1 == arg2:
            return 42
        else:
            return None

The logic is nonsensical - ignore it. What I am trying to so is to call an instance method from another instance method - and I am getting a NameError. I originally thought that this was due to foo()calling foobar()before it had been defined - but switching the order of the function definitions in the script made no difference.

逻辑是荒谬的 - 忽略它。我想要做的是从另一个实例方法调用一个实例方法 - 我得到了一个NameError. 我最初认为这是由于在定义之前foo()调用foobar()- 但切换脚本中函数定义的顺序没有任何区别。

Does anyone what's causing this error, and how to fix it?

有没有人是什么导致了这个错误,以及如何解决它?

采纳答案by Glenn Maynard

Python doesn't scope code to the local class automatically; you need to tell it to.

Python 不会自动将代码范围限定为本地类;你需要告诉它。

pp = self.foobar(arg1, arg2)

http://docs.python.org/tutorial/classes.html

http://docs.python.org/tutorial/classes.html