java - 类、方法、实例创建和 Main 相当于 Python 中的 Java

标签 java python python-2.7 python-3.x

我正在尝试使用 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/

相关文章:

java - Java剪辑在第一次播放时滞后

python - Pandas - 将括号中带有值的文本拆分为多列

python - 如何设置seaborn箱线图的y轴范围?

python - 存储大量数据的最智能方式

python - Python 中修饰函数和方法之间的行为差​​异

python - 如何区分 bool 和 z3 表达式?

java - Android:onConnectionToInternet

javascript - 使用 Java rest api 在 javascript 中发布请求不起作用

java - 如何捕获未经检查的事务异常

python - 为什么当将元组元素放入 Queue.PriorityQueue 时,元组元素的 __cmp__ 用于元组本身?