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.

Robert
  • 2,189
  • 6
  • 31
  • 38
  • No, it is not the compiler that throws that exception. It is the Python interpreter loop that does that. – Martijn Pieters Jul 09 '13 at 20:07
  • Why would you call a() from inside the class definition? – Travis DePrato Jul 09 '13 at 20:11
  • @TravisGD I always do this in Java, such as a method is called in another method... – Robert Jul 09 '13 at 20:16
  • No, I meant the bottom line. You call a() inside the class definition. Outside a method, inside the definition. – Travis DePrato Jul 09 '13 at 20:17
  • 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). – Bakuriu Jul 09 '13 at 20:28

1 Answers1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343