Home > Enterprise >  Python, create a kind of template for functions
Python, create a kind of template for functions

Time:09-30

I have a class with three functions that do almost the same things but on different objects. And I think there is a better way to program it since it is a duplication of code, but I cannot see how to have a kind of template. Here is my example:

    def averageEndEffectorVelocity(self, samplingSize=cst.AVERAGE_SIZE):
        if len(self.eeVelocity) < samplingSize:
            return -1
        else:
            return sum(self.eeVelocity[-samplingSize:])/samplingSize

    def averageEndEffectorAcceleration(self, samplingSize=cst.AVERAGE_SIZE):
        if len(self.eeAcceleration) < samplingSize:
            return -1
        else:
            return sum(self.eeAcceleration[-samplingSize:])/samplingSize

    def averageEndEffectorJerk(self, samplingSize=cst.AVERAGE_SIZE):
        if len(self.eeJerk) < samplingSize:
            return -1
        else:
            return sum(self.eeJerk[-samplingSize:])/samplingSize

One can see that each function is calculating the average of the last samplingSize values of the velocity, acceleration and jerk. Is there a way to have a better code?

CodePudding user response:

Make this function work fully on parameters passed to it (can be made class or static method, or refactored outside of the class completely):

def averageEndEffector(data, samplingSize=cst.AVERAGE_SIZE):
    if len(data) < samplingSize:
        return -1
    else:
        return sum(data[-samplingSize:])/samplingSize

Now all your instance methods can simply take the form of:

    def averageEndEffectorVelocity(self, samplingSize=cst.AVERAGE_SIZE):
        return averageEndEffector(data=self.eeVelocity, samplingSize=cst.AVERAGE_SIZE)

CodePudding user response:

You can combine to one method like this

def averageEndEffector(self, effector, samplingSize=cst.AVERAGE_SIZE):
    value = getattr(self, effector)
    if len(value) < samplingSize:
        return -1
    else:
        return sum(value[-samplingSize:])/samplingSize

effector can be eeVelocity, eeAcceleration or eeJerk (You can remove 'ee' and add this prefix to getattr function and it's better to use const)

  • Related