Home > Article > Backend Development > Why Am I Getting a \"NameError: name is not defined\" Error When Using a Class in Python?
Python NameError: Troubleshooting Undefined Class
When encountering the "NameError: name is not defined" error in Python, it often indicates that the program is attempting to use a variable or class that has not been defined or imported. In this instance, the code illustrates the error:
<code class="python">s = Something() Something.out() class Something: def out(): print("it works")</code>
Error Explanation:
The class definition for Something is placed after the line where you attempt to create a new instance of Something. This means that when the interpreter reaches the line s = Something(), the class Something has not yet been defined.
Solution:
To resolve this issue, you should always define classes before attempting to use them. In this case, move the class definition before the line where you create the Something instance:
<code class="python">class Something: def out(): print("it works") s = Something() Something.out()</code>
Passing Self to Instance Methods:
In the provided code, the out method is missing the self parameter. Instance methods in classes require self as the first argument, which represents the instance of the class itself. To correct this, you need to modify the out method definition to include self:
<code class="python">class Something: def out(self): print("it works")</code>
The above is the detailed content of Why Am I Getting a \"NameError: name is not defined\" Error When Using a Class in Python?. For more information, please follow other related articles on the PHP Chinese website!