add a setter to a subclass in python

To add a setter to a subclass in python, you can define a method with the same name as the attribute you want to set, and decorate it with the @property decorator to make it a setter method.

Here's an example:

main.py
class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

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

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

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        self._age = value


class Employee(Person):
    def __init__(self, name, age, salary):
        super().__init__(name, age)
        self._salary = salary

    @property
    def salary(self):
        return self._salary

    @salary.setter
    def salary(self, value):
        self._salary = value
638 chars
35 lines

In this example, we have a base class Person with two attributes: name and age, each with a getter and a setter method. We then define a subclass Employee that inherits from Person and adds a new attribute salary, also with a getter and a setter method.

Note that in the subclass Employee, we use the super() function to call the constructor of the base class and initialize the name and age attributes. We then define a new setter method for the salary attribute using the same @property and @salary.setter decorators.

gistlibby LogSnag