pythonfunctionclassvariablessimplify

How to combine multiple similar functions inside a class into, referencing to attributes inside the class


In the code below you see multiple functions doing almost the same thing yet for another attribute of this class

class IDManager():
    def __init__(self):

        self.inputIDs = []
        self.outputIDs = []
        self.operatorIDs = []
        self.dataManagerIDs = []
        self.timeManagerIDs = []

    def setIDS(self, min, max):
        self.inputIDs = list(range(min, max))

    def setOutputIDS(self, min, max):
        self.outputIDs = list(range(min, max))

    def setOperatorIDS(self, min, max):
        self.operatorIDs = list(range(min, max))

    def setDataManagerIDS(self, min, max):
        self.dataManagerIDs = list(range(min, max))

    def setTimeManagerIDS(self, min, max):
        self.timeManagerIDs = list(range(min, max))

This looks very messy to me. It made me wonder wether, when adding a type-variable to the functions, it is possible to simply it into one function. The example bellow clearly doesn't work since the type in self.type is now looking for a different attribute.

def setIDS(self, type, min, max):
            self.type = list(range(min, max))

Solution

  • What about setting the attribute directly:

    class IDManager():
        def __init__(self):
    
            self.inputIDs = []
            self.outputIDs = []
            self.operatorIDs = []
            self.dataManagerIDs = []
            self.timeManagerIDs = []
    
        def set_XXX_ID(self, min, max, XXX_attr):
            setattr(self, XXX_attr, list(range(min, max)))
    
    

    You can then call it with the attribute name, like for example:

    myIDManager = IDManager()
    myIDManager.set_XXX_ID(0, 10, 'dataManagerIDs')