Back to Freecodecamp

Step 21

curriculum/challenges/english/blocks/workshop-salary-tracker/68c809c990f253912a9e9209.md

latest2.4 KB
Original Source

--description--

As you learned in a previous lesson, a setter offers a way to control how an attribute can be modified. To ensure that new_name is the right type, create an if statement that raises a TypeError with the message 'name' must be a string. when new_name is not an instance of str.

--hints--

You should have an if statement inside your name setter.

js
({ test: () => assert(runPython(`_Node(_code).find_class("Employee").find_functions("name")[1].find_ifs()[0]`)) })

You should raise a TypeError with the message 'name' must be a string. when new_name is not an instance of str.

js
({ test: () => runPython(`
  emp = Employee('Frank', 'trainee')
  non_names = [0, True, []]
  for i in non_names:
    try:
      emp.name = i
    except TypeError as e:
      assert str(e) == "'name' must be a string."
    else:
      assert False, "Expected to raise TypeError with non-string new_name"
`) })

You should not raise any exception when new_name is a string.

js
({ test: () => runPython(`
  emp = Employee('Frank', 'trainee')
  try:
    emp.name = "Jack"
  except Exception:
    assert False, "Expected not to raise any exception with valid new_name"
    
`) })

--seed--

--seed-contents--

py
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}')"

    @property
    def name(self):
        return self._name
--fcc-editable-region--
    @name.setter
    def name(self, new_name):
        
        self._name = new_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}')