Python: when should you use subclasses instead of methods?

Viewed 737

Let's say I'm trying to make a class of two search algorithms, binary search and linear search. The way I see it there are three ways to do this.

Option 1: Make a class Search() with two methods binary_search and linear_search. The search algorithm would then depend on which method a user chooses to use. Example: the user would create the object s = Search() followed by usage of s.binary_search().

Option 2: Make a class Search() with a method do_search that calls on two private methods _binary_search and _linear_search based on what value is passed to an __init__ argument. Example: the user would create the object b = Search('binary').

Option 3: Make a base class Search() with two subclasses Binary() and Linear(). The user would then choose an algorithm by using the appropriate subclass. Example: the user would create the object b = Binary().

My question is which one of the three options should you use and why?

I think from a design perspective Option 3 is best, but I'm not really sure why. And I am interested about other perspectives as well (not just design).

1 Answers
Related