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.py638 chars35 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