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

1

43

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.

Artair answered 9/7, 2013 at 20:5 Comment(5)
No, it is not the compiler that throws that exception. It is the Python interpreter loop that does that.Paradise
Why would you call a() from inside the class definition?Currin
@TravisGD I always do this in Java, such as a method is called in another method...Artair
No, I meant the bottom line. You call a() inside the class definition. Outside a method, inside the definition.Currin
If you are used to Java forget it while you are learning/programming in python. Java is a completely different language; using its paradigms and conventions in python will only produce bad python code. In this case: in python methods are instance attributes exactly like anything else. If you want to access it you must first access the attribute from the instance via self.method_name. Without the explicit self how could you distinguish between a global function and a method(note: functions can be created at runtime -> it's impossible).Frogman
P
77

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.

Paradise answered 9/7, 2013 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.