Wrong
Wrong

Reputation: 1263

Should I put the main in a class in Python?

So far I've running the main() module in a script way (different .py file and not in a class or whatever) and then call the different instances from my other modules.

Is this right or should I make a class just for the main too?

Regards and thank.

Upvotes: 2

Views: 2203

Answers (2)

Stop harming Monica
Stop harming Monica

Reputation: 12620

If you don't know whether you need a new class then you should not write it.

Upvotes: 0

machine yearning
machine yearning

Reputation: 10119

You're overthinking it. Don't shoe-gaze over stuff that doesn't have a clear purpose. If you find a good reason to put a "main" function in a class, go ahead. Otherwise just save yourself the trouble.

To answer your question directly, I've never seen the "main" method defined in a class in python. The "main" function is usually just a driver for whatever you want to do with your program. It's something you want to execute every time your program is called. There's no general reason to represent this as an abstract data type, so I don't see the sense in encapsulating it in a class.

The python idiom I've seen most is to check if __name__ == "__main__":, which allows you to run a block of code only if the module is called directly, not as an include to another file. For example:

if __name__ == "__main__":
    print "This module was called directly."

You can see the question What does if __name__ == “__main__”: do? for more details.

Upvotes: 4

Related Questions