I've seen some people writing Python code by creating one class and then an object to call all the methods. Is there any advantage of using classes if we don't make use of inheritance, encapsulation etc? Such code seems to me less clean with all these 'self' arguments, which we could avoid. Is this practice an influence from other programming languages such as Java or is there any good reason why Python programs should be structured like this?
example code:
class App:
# all the methods go here
a = App()
One advantage, though not always applicable, is that it makes it easy to extend the program by subclassing the one class. For example I can subclass it and override the method that reads from, say, a csv file to reading an xml file and then instantiate the subclass or original class based on run-time information. From there, the logic of the program can proceed normally.
That of course raises the question of if reading the file is really the responsibility of the class or more properly belongs to a class that has subclasses for reading different types of data and presents a uniform interface to that data but that is, of course, another question.
Personally, I find that the cleanest way to do it is to put functions which make strong assumptions about their parameters on the appropriate class as methods and to put functions which make very weak assumptions about their arguments in the module as functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With