Search code examples
pythonpydev

Python main call within class


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?


Solution

  • 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()
    

    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()
    

    or

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