Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: NameError:global name '...‘ is not defined [duplicate]

in my code, I have:

class A:     def a():         ......      def b():         a()         ......     b() 

Then the compiler will say "NameError: global name a() is not defined." If I pull all the stuffs out of the class A, it would be no problem, but how can I define the method in class A? Thank you very much.

like image 767
Robert Avatar asked Jul 09 '13 20:07

Robert


People also ask

How do I fix NameError is not defined in Python?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

What is global name not defined in Python?

Python Nameerror name is not defined You will encounter a nameerror ( name is not defined) when a variable is not defined in the local or global scope. Or you used a function that wasn't defined anywhere in your program. For example, you will see this error if you try to print a variable that wasn't defined.

How do you define a global name in Python?

Global names: X , func. X is a global because it's assigned at the top level of the module file; it can be referenced inside the function without being declared global. func is global for the same reason; the def statement assigns a function object to the name func at the top level of the module. Local names: Y , Z.

What causes NameError in Python?

In Python, the NameError occurs when you try to use a variable, function, or module that doesn't exist or wasn't used in a valid way. Some of the common mistakes that cause this error are: Using a variable or function name that is yet to be defined.


1 Answers

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

like image 136
Martijn Pieters Avatar answered Sep 28 '22 00:09

Martijn Pieters