Back to Freecodecamp

Step 14

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

latest2.0 KB
Original Source

--description--

Now it's time to add some validation to the __init__ method. At the beginning of the method, create an if statement that checks if either name or level are not instances of str.

Inside the if statement, raise a TypeError with the message 'name' and 'level' attribute must be of type 'str'.

--hints--

You should have an if statement in your __init__ method.

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

Your if statement should check if either name and level are not instances of str.

js
({ test: () => runPython(`
  cond = _Node(_code).find_class("Employee").find_function("__init__").find_ifs()[0].find_conditions()[0]
  conditions = [
    "not (isinstance(name, str) and isinstance(level, str))",
    "not isinstance(name, str) or not isinstance(level, str)",
    "not (isinstance(level, str) and isinstance(name, str))",
    "not isinstance(level, str) or not isinstance(name, str)",
  ]
  assert any(cond.is_equivalent(c) for c in conditions)
`) })

Your if statement should raise a TypeError with the message 'name' and 'level' attribute must be of type 'str'.

js
({ test: () => assert(runPython(`_Node(_code).find_class("Employee").find_function("__init__").find_ifs()[0].find_bodies()[0].has_stmt('raise TypeError("\\'name\\' and \\'level\\' attribute must be of type \\'str\\'.")')`)) })

--seed--

--seed-contents--

py
class Employee:
--fcc-editable-region--
    def __init__(self, name, level):
        
        self._name = name
        self._level = level
--fcc-editable-region--
    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

    @property
    def level(self):
        return self._level

charlie_brown = Employee('Charlie Brown', 'trainee')
print(charlie_brown)