1

I'd like to raise a NotImplementedError when trying to set an attribute in a child class. Here's the code for the parent class:

class Parent():

    def __init__(self):
        self._attribute = 1

    @property
    def attribute(self):
        return self._attribute

    @attribute.setter
    def attribute(self, value):
        self._attribute = value

I see that I can define a Child which overwrites' Parent's attribute setter directly by doing any of the following:

class ChildA(Parent):

    @Parent.attribute.setter
    def attribute(self, value):
        raise NotImplementedError('Not implemented.')


class ChildB(Parent):

    @property
    def attribute(self):
        return self._attribute

    @attribute.setter
    def attribute(self, value):
        raise NotImplementedError('Not implemented.')

Is there a difference between any of the above?

Daniel
  • 11,332
  • 9
  • 44
  • 72
  • 1
    one question per ticket pls – Andersson Aug 16 '18 at 09:43
  • Aren't the questions way too related to merit 2 different threads? – Daniel Aug 16 '18 at 09:45
  • They don't look very related to me. You're essentially asking us to explain `property` *and* `super` to you. That's two questions. – Aran-Fey Aug 16 '18 at 09:46
  • Alright. fixed. – Daniel Aug 16 '18 at 09:47
  • Not sure what to do with this question now... We have boatloads of related questions that have been answered with the `@Parent.attribute.setter` solution, but I can't find a question that has asked if there's a difference between these two solutions. Should I just post an answer that says "No, there's no difference" and link to a few related questions? – Aran-Fey Aug 16 '18 at 09:56
  • If there is no difference, then by all means I'm happy to read about it on related questions, but I'd like to understand what is happening. Are both definitions mutating the parent behaviour or simply shadowing it? If `ChildA` mutates parent, does it influence Parent's instances? References about these issues would help me as well. Thanks! – Daniel Aug 16 '18 at 10:00

1 Answers1

1

There is no difference between those two solutions.

In fact, the @property.getter, @property.setter and @property.deleter decorators have been carefully designed with this exact use case in mind. From the docs:

A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.

(Emphasis mine.)

So no, using @Parent.attribute.setter won't affect the behavior of the Parent class.

Overall, it's better to use the @Parent.attribute.setter solution because it reduces code duplication - copy-pasting the parent class's getter into the child class is nothing but a potential source of bugs.


Related questions:

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149