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

Time:12-06

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))

CodePudding user response:

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')
  • Related