python 语法中的 Java 主类
这是一个带有 main 方法的 Java 类示例。
public class MyMainClass{
public static void main(){
doThings();
}
}
要启动它,我必须对其执行“javac”,然后对其输出执行“java”。
我最近用 python 做了很多实验,但我不知道如何构造我的 py 文档,使其像具有 main 函数的 Java 类一样运行。例如,我尝试像这样编写Python代码:
class MyClass:
def method(self):
print("in main")
def main():
mc = MyClass()
mc.method()
if __name__ == "__main__":
main()
但它不起作用。启动解释器时得到的输出是:
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
它的缩进有问题,或者我代表我承认逻辑错误。有人可以帮我编写一个看起来与 Java 类一模一样的 Python 主类吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
具有 main 方法的 Java 类的 Python 等效项是:
创建一个实例并调用其方法:
我认为令人困惑的是,您正在为程序使用 main() 函数,这不是必需的,但很好实践。但你的代码看起来不错。
The Python equivalent of your Java Class with a main method would be:
You create an instance and call its method:
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.
为什么不呢...
这是您将在这里得到的最接近 Java 的东西。
Why not...
That's the closest thing to Java that you'll get here.
我觉得没问题:
您遇到的问题是什么?
或者,您正在寻找类似以下的内容吗?
It seems OK to me:
What is the problem that you are experiencing?
Or, are you looking for something like the following?