[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Why can't access the property setter using the super?

On Wed, Mar 20, 2019 at 6:17 AM Arup Rakshit <ar at zeit.io> wrote:
> Hello Ian,
> That seems like too much code involved. Is this how we do write inheritance in Python. Coming from Ruby and JS world I find Python inheritance mechanism confusing so far. :/

Ian gave the longhand form, but you can omit the arguments to super()
if you're using it inside the class definition.

Something you may want to consider, though, is NOT overriding the
parent's setter. Instead, have a validation step prior to the actual
setting, which you could then override in a subclass. Something like

class RefrigeratedShippingContainer(ShippingContainer):
    def _validate_temp(self, value):
        """Ensure that the given temperature is valid for this container

        Invariant: At all times, self.validate_temp(self.celsius) will
not raise.
        if value > RefrigeratedShippingContainer.MAX_CELSIUS:
            raise ValueError("Temperature too hot!")

    def celsius(self):
        return self._celsius

    def celsius(self, value):
        self._celsius = value

class HeatedRefrigeratedShippingContainer(RefrigeratedShippingContainer):
    MIN_CELSIUS = -20.0

    def _validate_temp(self, value):
        if value < HeatedRefrigeratedShippingContainer.MIN_CELSIUS:
            raise ValueError("Temperature too cold!")

Now, your property function doesn't need to care WHAT the validation
is, it just requests validation. You can redefine the validation logic
without changing anything else.