Search code examples
pythonpython-3.xooppropertiesoverriding

Override a property with super()


I would like to override this parent property to make it conditional with a flag:

@property
def velocity(self):
    """Instantaneous velocity in km/h."""
    if self.time is not None:
        dt = np.diff(self.seconds)
        dd = np.diff(self.distance)
        vs = 3600 * dd / dt
        return self._resample(vs, self.seconds)
    else:
        return None

I can do this easily with something like this in the child:

@property
def velocity(self, flag=True):
    if flag:
        if self.time is not None:
            dt = np.diff(self.seconds)
            dd = np.diff(self.distance)
            vs = 3600 * dd / dt
            return self._resample(vs, self.seconds)
        else:
            return None

But shouldn't I be also able to do just this instead of copying the code vebatim? If I do that the "supered" function always returns None, no matter the flag or that self.time has not changed (and is not None):

@property
def velocity(self, flag=True):
    if flag:
        super().velocity

Solution

  • Try return super().velocity

    @property
    def velocity(self, flag=True):
        if flag:
            return super().velocity