1

I have been coding in python for a couple months now, and something has always been on my mind. I know you can have classes in your .py file, but you don't have to. My question is, is it good practice to always have your code in a class, or is it not necessary?

FYI: I have been coding in Java for a few years, so I'm used to always having a "main" class and a main method that runs everything.

Paolo
  • 20,112
  • 21
  • 72
  • 113
Linny
  • 818
  • 1
  • 9
  • 22
  • 4
    Python supports multiple programming [paradigms](https://blog.newrelic.com/2015/04/01/python-programming-styles/). If you think your program is better suited for a `class`, then use it; it is not a requirement. – pstatix Jul 22 '18 at 22:07
  • 1
    This seems like something you might be interested in: https://youtu.be/o9pEzgHorH0 – Ilja Everilä Jul 22 '18 at 22:09

1 Answers1

1

It depends on what your file is. In theory everything (saying this with some hesitation) can be written as a class. But it is a bit overkill to do that just for the sake of being "correct" and will probably make your code look strange rather than clear. In general i would make the following distinctions between cases

  1. If it is the source for a big project which makes sense to be organized in an object oriented fashion, then you would have a class which defines exactly that. This is great because then you can inherit the class for variants or child projects.
  2. If you are creating a list of utility functions to use for all your projects, such as array manipulations or little tools that are always handy, then a function-only file is the way to go
  3. If you are writing a script which is designed in order to execute a specific task in the way a script would, then i would define task-specific source in a .py file and include the code related to the execution under the statement

    if name == 'main':

papayiannis
  • 114
  • 5