Daniel
Daniel

Reputation: 12076

Understanding inheritance of parent's attribute setter

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?

Upvotes: 1

Views: 162

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43326

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:

Upvotes: 1

Related Questions