"NameError: name is not defined"... but it is?
python - How to avoid "NameError: name is not defined" when using a class above its definition - Stack Overflow
NameError: name '' is not defined
Keep getting Nameerror: name error is not defined - Python - Code with Mosh Forum
Videos
Define the class before you use it:
class Something:
def out(self):
print("it works")
s = Something()
s.out()
You need to pass self as the first argument to all instance methods.
Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.
class Tree:
def __init__(self, left: Tree, right: Tree):
self.left = left
self.right = right
This will also result in
NameError: name 'Tree' is not defined
That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.
class Tree:
def __init__(self, left: 'Tree', right: 'Tree'):
self.left = left
self.right = right
When you click run (in pycharm) it executes the file in a different instance of python for debugging and all that. The python console window, is totally different. Its not linked to your code. Its there to execute python commands and tests stuff just like you would do in IDLE.
When you do Execute Selection in Console, this basically executes your file in the console instead of running it on its own.
Its something like this you would do in IDLE when you want to execute your file:
exec(open("mycode.py").read())
Edit: In your python console, you can execute the above command to load your file in the console. But this is basically the same thing as selecting Execute Selection in Console
switch your interpreter from python 2.7 to 3.1 and will solve the problem, you can do this by going to the settings of the ide or calling python 3.(version) in command line