我正在尝试使用 class 实现示例 python 程序,使用 main 方法创建一些方法和实例(对象创建)。但我是 python 的新手,我尝试了很多示例,但我没有在 python 中得到上面的确切流程。下面是我需要在 python 中等效的 java 代码。
Class hello { //Class name
void display () { // user defined method
System.out.println("Hello");
}
public static void main(String args[]) { //main method
hello obj=new hello(); //instance creation (object creation)
obj.display(); // invoking methods
}
}
输出
Hello
我需要上面的 python 代码,请帮我解决这个问题
我用同样的 python 尝试过
import sys
class MyApplication():
def get_name():
print 'hi'
def main():
app=MyApplication()
print('Hi ' + app.get_name())
if __name__ == '__main__':
main()
但是上面的 python 代码不工作,没有给出任何错误和输出。我得到的是空白控制台
最佳答案
在python中,意图非常重要。如果您想要一些代码段,则意味着该代码段是 block 的一部分。
请参阅您的代码中的以下片段
def main():
app=MyApplication()
print('Hi ' + app.get_name())
if __name__ == '__main__':
main()
您应该更正此代码段的缩进。应该是,
def main():
app = MyApplication()
print('Hi ' + app.get_name())
if __name__ == '__main__':
main()
'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported: A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported: - Python documentation
关于java - 类、方法、实例创建和 Main 相当于 Python 中的 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37002841/