Class with too many parameters: better design strategy?

UPDATE: This approach may be suited in your specific case, but it definitely has its downsides, see is kwargs an antipattern?

Try this approach:

class Neuron(object):

    def __init__(self, **kwargs):
        prop_defaults = {
            "num_axon_segments": 0, 
            "apical_bifibrications": "fancy default",
            ...
        }
        
        for (prop, default) in prop_defaults.iteritems():
            setattr(self, prop, kwargs.get(prop, default))

You can then create a Neuron like this:

n = Neuron(apical_bifibrications="special value")

I'd say there is nothing wrong with this approach - if you need 15 parameters to model something, you need 15 parameters. And if there's no suitable default value, you have to pass in all 15 parameters when creating an object. Otherwise, you could just set the default and change it later via a setter or directly.

Another approach is to create subclasses for certain common kinds of neurons (in your example) and provide good defaults for certain values, or derive the values from other parameters.

Or you could encapsulate parts of the neuron in separate classes and reuse these parts for the actual neurons you model. I.e., you could write separate classes for modeling a synapse, an axon, the soma, etc.


You could perhaps use a Python"dict" object ? http://docs.python.org/tutorial/datastructures.html#dictionaries