Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python main call within class

Tags:

python

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

and

main() 

and

main(self) 

none of which work. What am I missing?

like image 936
franka Avatar asked Oct 24 '11 02:10

franka


People also ask

How do you call a main function inside a class in Python?

To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.

Should main be in a class Python?

No you shouldn't. You can put your main function in the same file as a class, but there's no reason to nest it inside the class.

What Does main () do in Python?

The main function in Python acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.

Does Python have a main () method?

Since there is no main() function in Python, when the command to run a Python program is given to the interpreter, the code that is at level 0 indentation is to be executed.


2 Answers

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!" 
like image 69
Amber Avatar answered Sep 26 '22 02:09

Amber


That entire block is misplaced.

class Example(object):     def main(self):              print "Hello World!"  if __name__ == '__main__':     Example().main() 

But you really shouldn't be using a class just to run your main code.

like image 41
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 02:09

Ignacio Vazquez-Abrams