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 (mos开发者_Go百科t 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?
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.
It seems OK to me:
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass:
... def method(self):
... print("in main")
...
>>> def main():
... mc = MyClass()
... mc.method()
...
>>> if __name__ == "__main__":
... main()
...
in main
What is the problem that you are experiencing?
Or, are you looking for something like the following?
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass:
... @staticmethod
... def main():
... print("in main")
...
>>> if __name__ == "__main__":
... MyClass.main()
...
in main
The Python equivalent of your Java Class with a main method would be:
class MyClass:
def main(self):
print("in main")
doThings()
You create an instance and call its method:
mc = MyClass()
mc.main()
I think the confusion is that you are using a main() function for your program, which isn't necessary, but is good practice. But your code seems fine.
精彩评论