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

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

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.

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

回答1:

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

pp = self.foobar(arg1, arg2) 

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!