📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    The following Python code intends to enforce that all

    `Worker` subclasses implement a `work` method. However, it's not working as expected. class Worker:     def work(self):         raise NotImplementedError("Subclasses must implement this method") class Engineer(Worker):     pass eng = Engineer() eng.work() What is the most Pythonic way to fix this to ensure `Engineer` *must* implement `work` at compile/definition time?
    A Add `@abstractmethod` decorator to `work` in `Worker` and inherit from `ABC`. Correct Answer Incorrect Answer
    B Add `assert False, "Implement work"` in `Engineer.work`. Correct Answer Incorrect Answer
    C Change `Worker` to an interface. Correct Answer Incorrect Answer
    D Manually check for `work` method in `Engineer` after its definition. Correct Answer Incorrect Answer
    E Make `work` a private method in `Worker`. Correct Answer Incorrect Answer

    Solution

    o The original Worker class uses NotImplementedError, which is a runtime check. The error only occurs when eng.work() is actually called. o To enforce that Engineer must implement work at the time the Engineer class is defined (or instantiated), you need to use Python's Abstract Base Classes (ABCs). o By inheriting Worker from abc.ABC and decorating work with @abstractmethod, Worker becomes an abstract class. Any concrete subclass (like Engineer) that fails to implement work will raise a TypeError when you try to instantiate it (e.g., eng = Engineer()).

    Practice Next
    ask-question