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.
python - How to avoid "NameError: name is not defined" when using a class above its definition - Stack Overflow
"NameError: name is not defined"... but it is?
python - NameError: name 'i' is not defined - Why does this happen? - Stack Overflow
Name error : 'name' is not defined
How to solve undefined variable in python
What causes undefined variable?
Videos
Hello,
I'm new to coding and don't know what I am doing wrong here. I am using VS Code, and below is what I've inputted. Only "john" and "programmer" are highlighted in red font, while the remaining code is either blue, green, or yellow. From my understanding, those phrases are causing the syntax error. Also, it works fine when I run the same code in IDLE Shell.
name = "john"
age = 21
weight = 160.1
occupation = "programmer"
>>>print(name, age, weight, occupation)
---->Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
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