Python 类内的 main 调用
我没有做过太多Python工作——来自C/Java背景——所以请原谅我问这么一个简单的问题。我在 Eclipse 中使用 Pydev 来编写这个简单的程序,我想要它做的就是执行我的 main 函数:
class Example():
if __name__ == '__main__':
Example().main() <----- What goes here?
def main(self):
print "Hello World!
这就是我现在所拥有的。我也尝试过
self.main()
,
main()
但
main(self)
都不起作用。我缺少什么?
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()
and
main()
and
main(self)
none of which work. What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您需要实际定义一个函数,然后才能运行它(并且不需要将其称为
main
)。例如:但是,您不需要使用类 - 如果您只想运行一些代码,只需将其放入函数中并调用该函数,或者只需将其放入
if
块:或
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: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:or
整个块都放错了地方。
但你真的不应该使用类只是为了运行你的主代码< /a>.
That entire block is misplaced.
But you really shouldn't be using a class just to run your main code.
请记住,您不可以这样做。
您必须从类外部或该类的函数内部调用类函数。
Remember, you are NOT allowed to do this.
You must call a class function from either outside the class, or from within a function in that class.