0

This question arises from reading the answer to Overriding an inherited property setter. Assume the case where I have the base Person class:

class Person:
    def __init__(self, name):
        self.name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

Following the top-voted answer the correct way to override the setter would be:

class Superhero(Person):
    def __init__(self, name):
        super().__init__(name)

    @Person.name.setter
    def name(self, value):
        Person.name.fset(self, "Super " + value)

Would there be a difference if instead, the Superhero class updated the _name attribute directly? i.e.

class Superhero(Person):
    def __init__(self, name):
        super().__init__(name)

    @Person.name.setter
    def name(self, value):
        self._name = "Super " + value

(I know, a comment in the referenced question would have been enough but due to reputation I do not have the privileges to ask.)

Ramon
  • 501
  • 3
  • 13
  • 1
    Did you try it? What happened? I'd expect it to work, but now the child has to know what the backing attribute is named too. – jonrsharpe Sep 23 '20 at 19:21
  • Yes, I tried and it worked. I get your point, better the to stick to the fset since there is no need to know how the property is named. – Ramon Sep 23 '20 at 19:32

0 Answers0