Class with too many parameters: better design strategy?

后端 未结 13 925
醉酒成梦
醉酒成梦 2020-12-04 08:29

I am working with models of neurons. One class I am designing is a cell class which is a topological description of a neuron (several compartments connected together). It ha

13条回答
  •  攒了一身酷
    2020-12-04 08:34

    could you supply some example code of what you are working on? It would help to get an idea of what you are doing and get help to you sooner.

    If it's just the arguments you are passing to the class that make it long, you don't have to put it all in __init__. You can set the parameters after you create the class, or pass a dictionary/class full of the parameters as an argument.

    class MyClass(object):
    
        def __init__(self, **kwargs):
            arg1 = None
            arg2 = None
            arg3 = None
    
            for (key, value) in kwargs.iteritems():
                if hasattr(self, key):
                    setattr(self, key, value)
    
    if __name__ == "__main__":
    
        a_class = MyClass()
        a_class.arg1 = "A string"
        a_class.arg2 = 105
        a_class.arg3 = ["List", 100, 50.4]
    
        b_class = MyClass(arg1 = "Astring", arg2 = 105, arg3 = ["List", 100, 50.4])
    

提交回复
热议问题