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?
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).
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With