Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason for using classes in Python if there is only one class in the program?

Tags:

python

oop

class

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()    
like image 640
Siato Avatar asked Oct 21 '10 00:10

Siato


1 Answers

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.

like image 198
aaronasterling Avatar answered Oct 09 '22 17:10

aaronasterling