Search code examples
javapythoncomparisonclass-design

Java main-class in python-syntax


this is an example Java Class with a main method.

public class MyMainClass{
    public static void main(){
        doThings();
    }
}

To start it i have to do a "javac" on it and then a "java" on its output.

I've been experimenting quite a bit with python lately, but i couldn't figure out how to structure my py-document to function exactly like a Java Class with main function. For example i tried to code Python like this:

class MyClass:
    def method(self):
        print("in main")

def main():
    mc = MyClass()
    mc.method()

if __name__ == "__main__":
    main()

But it doens't work. The output i get when starting the interpreter is:

   C:\Users\altug>python MyClass.py
   Traceback (most recent call last):
   File "MyClass.py", line 9, in <module>
   main()
   NameError: name 'main' is not defined

Something is wrong with its indentation or i admit even logical errors on my behalf. Can someone help me to code a Python-main-class that looks exactly like a Java class?


Solution

  • Why not...

    class MyClass:
        def method(self):
            print("in main")
    
    if __name__ == "__main__":
        MyClass().method()
    

    That's the closest thing to Java that you'll get here.