简体   繁体   中英

Python: Separate class methods from the class in an own package

I wrote a class with many different parameters, depending on the parameter the class uses different actions.

I can easily differentiate my methods into different cases, each set of methods belonging to certain parameters.

This resulted in a huge .py file, implementing all methods in the one class. For better readability, is it possible to write multiple methods in an own file and load it (similar as a package) into the class to treat them as class methods?

To give more details, my class is a decision tree. A parameter for example is the pruning method, used to shrink the tree. As I use different pruning methods, this takes a lot of lines in my class. I need to have a set of methods for each pruning parameter. It would be nice to simply load the methods for pruning from another file into the class and therefore shrinking the size of my decision tree .py file.

For better readability, I got a few suggestions.

  1. Collapse all functions definitions, which can easily be achieved by one click in most of the popular text editors.
  2. Place related methods next to each other.
  3. Give proper names to categorise and differentiate methods, for example.

    def search_board_first(): pass

    def search_deep_first(): pass

Regarding splitting a huge class into a Object oriented behaviour, my rule of thumb is to consider the re-usability. If functions can be reused by other classes, they should be put in separate files and make them independent(static) of other classes.

If the methods are tied to the class and no where else, it is better to just to enclose that method within the class itself. Think it this way, to review the code, you need to refer the class properties anyway. Logically it doesn't quite make sense to split files just for splitting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM