Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: NameError: global name 'foobar' is not defined [duplicate]

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?

like image 565
skyeagle Avatar asked Nov 01 '10 12:11

skyeagle


People also ask

Why is my name not defined in Python?

You now have a guide to understand why the error “NameError: name … is not defined” is raised by Python during the execution of your programs. The Python NameError happens if you use a variable without declaring it. Make sure a variable or function is declared before being used in your code (and not after).

What is nameerror in Python?

NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are : Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

What is the cause of nameerror?

NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are : 1. Misspelled built-in functions: In the below example code, the print statement is misspelled hence NameError will be raised.

What happens if only the nameerror is raised in the try-block?

In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console. return "NameError occurred. Some variable isn't defined." NameError occurred. Some variable isn't defined.


Video Answer


1 Answers

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

like image 181
Glenn Maynard Avatar answered Sep 20 '22 23:09

Glenn Maynard