Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are verbose __init__ methods in Python bad?

Tags:

python

oop

I have a program that I am writing in Python that does the following:

The user enters the name of a folder. Inside that folder a 8-15 .dat files with different extensions.

The program opens those dat files, enters them into a SQL database and then allows the user to select different changes made to the database. Then the database is exported back to the .dat files. There are about 5-10 different operations that could be performed.

The way that I had planned on designing this was to create a standard class for each group of files. The user would enter the name of the folder and an object with certain attributes (file names, dictionary of files, version of files (there are different versions), etc) would get created. Determining these attributes requires opening a few of these files, reading file names, etc.

Should this action be carried out in the __init__ method? Or should this action be carried our in different instance methods that get called in the __init__ method? Or should these methods be somewhere else, and only be called when the attribute is required elsewhere in the program?

I have already written this program in Java. And I had a constructor that called other methods in the class to set the object's attributes. But I was wondering what standard practice in Python would be.

like image 854
Tim Brooks Avatar asked Mar 12 '12 14:03

Tim Brooks


2 Answers

Well, there is nothing special about good OOP practices in Python. Decomposition of one big method into a bunch of small ones is great idea both in Java and in Python. Among other things small methods gives you an opportunity to write different constructors:

class GroupDescriptor(object):
    def __init__(self, file_dictionary):
        self.file_dict = file_dictionary
        self.load_something(self.file_dict['file_with_some_info'])

    @classmethod
    def from_filelist(cls, list_of_files):
        file_dict = cls.get_file_dict(list_of_files)
        return cls(file_dict)

    @classmethod
    def from_dirpath(cls, directory_path):
        files = self.list_dir(directory_path)
        return cls.from_filelist(files)

Besides, I don't know how it is in Java but in Python you don't have to worry about exceptions in constructor because they are finely handled. Therefore, it is totally normal to work with such exception-prone things like files.

like image 193
Kirill Avatar answered Oct 23 '22 05:10

Kirill


It looks the action you are describing are initialization, so it'd be perfectly ok to put them into __init__. On the other hand, these actions seem to be pretty expensive, and probably useful in the other part of a program, so you might want to encapsulate them in some separate function.

like image 30
Roman Bodnarchuk Avatar answered Oct 23 '22 05:10

Roman Bodnarchuk