类内的 Python 主调用 [英] Python main call within class

查看:47
本文介绍了类内的 Python 主调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有做过很多 python - 来自 C/Java 背景 - 所以请原谅我问这么简单的问题.我在 Eclipse 中使用 Pydev 来编写这个简单的程序,我想要它做的就是执行我的主要功能:

I haven't done much python - coming from a C/Java background - so excuse me for asking such a simple question. I am using Pydev in Eclipse to write this simple program, and all I want it to do is to execute my main function:

class Example():

if __name__ == '__main__':
    Example().main()        <----- What goes here?


    def main(self):     
        print "Hello World!

这就是我现在所拥有的.我也试过

That is what I have now. I have also tried

self.main() 

main()

main(self)

没有一个工作.我错过了什么?

none of which work. What am I missing?

推荐答案

嗯,首先,你需要真正定义一个函数,然后你才能运行它(而且它不需要被调用main).例如:

Well, first, you need to actually define a function before you can run it (and it doesn't need to be called main). For instance:

class Example(object):
    def run(self):
        print "Hello, world!"

if __name__ == '__main__':
    Example().run()

不过,您不需要使用类 - 如果您只想运行一些代码,只需将其放入函数中并调用该函数,或者将其放入 if 块:

You don't need to use a class, though - if all you want to do is run some code, just put it inside a function and call the function, or just put it in the if block:

def main():
    print "Hello, world!"

if __name__ == '__main__':
    main()

if __name__ == '__main__':
    print "Hello, world!"

这篇关于类内的 Python 主调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆