curriculum/challenges/english/blocks/workshop-salary-tracker/68c8002beb157fe47d2e7699.md
A setter is a method used to set the value of an attribute, allowing for validation checks and restrictions. You can create a setter using the @propertyName.setter decorator, where propertyName should match the name of the property to set:
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
p = Person('Alice')
p.name = 'Abigail' # Calls the setter
print(p.name) # Abigail
After your getter method, create a name method with parameters self and new_name. Decorate the method with @name.setter. Inside the method, set self._name to new_name.
Your Employee class should have a name method with parameters self and new_name.
({ test: () => assert(runPython(`_Node(_code).find_class("Employee").find_functions("name")[1].has_args("self, new_name")`)) })
Your name method should be decorated with @name.setter.
({ test: () => assert(runPython(`_Node(_code).find_class("Employee").find_functions("name")[1].has_decorators("name.setter")`)) })
Your name method should set self._name to new_name.
({ test: () => assert(runPython(`_Node(_code).find_class("Employee").find_functions("name")[1].has_stmt("self._name = new_name")`)) })
class Employee:
_base_salaries = {
'trainee': 1000,
'junior': 2000,
'mid-level': 3000,
'senior': 4000,
}
def __init__(self, name, level):
if not (isinstance(name, str) and isinstance(level, str)):
raise TypeError("'name' and 'level' attribute must be of type 'str'.")
if level not in Employee._base_salaries:
raise ValueError(f"Invalid value '{level}' for 'level' attribute.")
self._name = name
self._level = level
self._salary = Employee._base_salaries[level]
def __str__(self):
return f'{self.name}: {self.level}'
def __repr__(self):
return f"Employee('{self.name}', '{self.level}')"
--fcc-editable-region--
@property
def name(self):
return self._name
--fcc-editable-region--
@property
def level(self):
return self._level
@property
def salary(self):
return self._salary
charlie_brown = Employee('Charlie Brown', 'trainee')
print(charlie_brown)
print(f'Base salary: ${charlie_brown.salary}')