PCPP2 study materials
PCPP2 study resources

PCPP2 practice questions

One question at a time. Build your PCPP2 understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Testing principles and techniques (unittest and pytest frameworks)

In a `unittest.TestCase` subclass, which method name prefix causes the test runner to discover and execute a method as a test?

  1. test Correct answer.
  2. assert
  3. verify
  4. check

Explanation

The standard unittest loader treats any method whose name begins with `test` as a test case and executes it automatically. Other prefixes such as `check` or `verify` are ignored by discovery unless a custom loader is configured. This convention is what lets a class inherit from TestCase and still control which methods run.

Question 2Testing principles and techniques (unittest and pytest frameworks)

Which `unittest` assertion method verifies that calling a callable raises a specific exception type while also allowing the exception object to be inspected, without requiring a regular-expression argument?

  1. assertRaises Correct answer.
  2. assertRaisesRegex
  3. assertRaisesContext
  4. assertWarns

Explanation

`assertRaises` can be used as a context manager, and the exception instance is bound to the `exception` attribute of the returned context object. That makes it possible to assert on the exception's type and inspect its attributes. `assertRaisesRegex` also exposes the exception in its context-manager form, but requires a regular expression to check the message.

Question 3Testing principles and techniques (unittest and pytest frameworks)

A test class defines `setUpClass` as a classmethod. When does it execute relative to the individual test methods in that class?

  1. Once before any test method in the class runs Correct answer.
  2. Once before each test method
  3. Once after all test methods in the class finish
  4. Only when a test method fails

Explanation

`setUpClass` is a class-level fixture that runs exactly once before the first test in the class executes, which suits expensive shared setup such as opening a database connection. It is paired with `tearDownClass`, which runs once after the last test. Per-test isolation belongs in `setUp`/`tearDown` instead.

Question 4Testing principles and techniques (unittest and pytest frameworks)

In pytest, which naming convention allows a function named `check_total` in a test module to be collected as a test?

  1. Move the function into a class named `Test`
  2. Nothing is needed; pytest collects any function in a test file
  3. Add `@pytest.mark.test` to the function
  4. Rename the module to `test_` prefix and configure `python_functions` to include `check_*` Correct answer.

Explanation

pytest collects functions matching `python_functions`, which defaults to `test*`. To collect `check_*` functions you must override that ini option, and the module itself must still match the `python_files` pattern such as `test_*.py`. Both conditions are required for collection.

Question 5Testing principles and techniques (unittest and pytest frameworks)

Which pytest fixture scope causes a fixture to be created once per test module and torn down after the last test in that module?

  1. session
  2. class
  3. module Correct answer.
  4. function

Explanation

The `module` scope creates the fixture value once for the entire module and finalizes it after the module's last test. `function` is the default and recreates per test, while `session` spans the whole run. Choosing the widest safe scope reduces expensive setup.

Question 6Testing principles and techniques (unittest and pytest frameworks)

A test uses `with pytest.raises(ValueError, match='negative'):` around a call. What does the `match` argument check?

  1. That the exception class name equals `negative`
  2. That the test function name contains `negative`
  3. That the exception's string representation matches the regex using `re.search` Correct answer.
  4. That the raised exception is a subclass of `MatchError`

Explanation

`match` applies `re.search` to the string form of the exception, so the pattern can appear anywhere in the message. It is not an exact-equality check, which is why anchoring with `^` and `$` is needed for strict matching. This keeps assertions resilient to incidental message changes.

Question 7Testing principles and techniques (unittest and pytest frameworks)

What is the purpose of `unittest.mock.patch` when used as a decorator on a test method?

  1. It permanently rebinds the target to a Mock for the whole process
  2. It replaces the target attribute with a Mock for the duration of the test and restores it afterward Correct answer.
  3. It records only calls made to the target and leaves the original callable in place
  4. It raises an error if the target is called during the test

Explanation

`patch` temporarily substitutes the named attribute with a `MagicMock`, then restores the original when the decorated test exits, even on failure. This isolates the code under test from real I/O or network dependencies. The mock is injected as an argument to the decorated function.

Question 8Testing principles and techniques (unittest and pytest frameworks)

A developer wants a pytest test to run only when an environment variable `CI` is set. Which built-in mechanism expresses this condition cleanly?

  1. `@pytest.mark.parametrize('CI', [True])`
  2. `pytest.ini` with `addopts = -k CI`
  3. `@pytest.mark.xfail(strict=True)`
  4. `@pytest.mark.skipif(not os.environ.get('CI'), reason='CI only')` Correct answer.

Explanation

`skipif` accepts a condition evaluated at collection time and skips the test when it is true, reporting the reason. `xfail` marks an expected failure rather than a conditional skip. Using `-k CI` filters by name and does not inspect the environment.

Question 9Testing principles and techniques (unittest and pytest frameworks)

Why is `pytest.approx` preferred over `==` when asserting a computed floating-point result?

  1. It compares values with a configurable relative or absolute tolerance Correct answer.
  2. It ignores the sign of the numbers
  3. It converts floats to fractions before comparing
  4. It rounds both operands to the nearest integer

Explanation

Binary floating-point arithmetic introduces representation error, so exact equality frequently fails for values like `0.1 + 0.2`. `pytest.approx` compares within a default relative tolerance of 1e-6, adjustable per assertion. This tests the property that matters without masking real deviations.

Question 10Testing principles and techniques (unittest and pytest frameworks)

A test class inherits from `unittest.TestCase` and defines a method `test_a`. If the class also defines `__init__(self, methodName)` without calling `super().__init__`, what is the most likely consequence?

  1. pytest refuses to collect any test in the file
  2. unittest fails to instantiate the test with the required `methodName` argument Correct answer.
  3. The test method is silently skipped
  4. The test still runs because unittest inspects attributes directly

Explanation

unittest instantiates each TestCase with the name of the method to run, so overriding `__init__` without forwarding `methodName` to the base breaks instantiation. The framework relies on that argument to bind the specific test. The fix is to avoid overriding `__init__` or to call `super().__init__(methodName)`.

Question 11Testing principles and techniques (unittest and pytest frameworks)

Which pytest feature allows a test to run against multiple input/output pairs without duplicating the test function?

  1. `@pytest.mark.parametrize('arg', [...])` Correct answer.
  2. `@pytest.mark.usefixtures('arg')`
  3. `@pytest.fixture(params=[...])` only
  4. `pytest.raises` with a list of arguments

Explanation

`parametrize` generates one test case per parameter set, each reported separately in the test output. Fixture params also produce multiple cases but are tied to fixture setup rather than direct test arguments. Parametrize is the standard tool for table-driven tests.

Question 12Testing principles and techniques (unittest and pytest frameworks)

A test needs a temporary directory that is automatically cleaned up after the test. Which pytest built-in fixture provides this?

  1. `monkeypatch`
  2. `capsys`
  3. `tmp_path` Correct answer.
  4. `request`

Explanation

`tmp_path` supplies a unique `pathlib.Path` directory per test invocation and removes it when the test finishes. It is function-scoped by default so tests cannot leak files into each other. `tmp_path_factory` serves session-scoped needs.

Question 13Testing principles and techniques (unittest and pytest frameworks)

What does the `side_effect` attribute of a `unittest.mock.Mock` do when set to an exception instance?

  1. It returns the exception object as the mock's return value
  2. It disables the mock after the first call
  3. It raises that exception each time the mock is called Correct answer.
  4. It records the exception in `call_args`

Explanation

Setting `side_effect` to an exception class or instance makes the mock raise it on every call, which is how tests simulate failure paths. A callable side effect, by contrast, is invoked and its return value used. This distinction is central to mocking error handling.

Question 14Testing principles and techniques (unittest and pytest frameworks)

A test uses `monkeypatch.setenv('MODE', 'test')`. What happens to the environment after the test completes?

  1. The variable is deleted only if the test passes
  2. The original environment is restored automatically Correct answer.
  3. The change persists only within the same module
  4. The variable remains set for subsequent tests

Explanation

`monkeypatch` records the prior state and undoes each change during fixture teardown, regardless of test outcome. This prevents cross-test contamination through global state. Manual `os.environ` edits would need explicit cleanup.

Question 15Testing principles and techniques (unittest and pytest frameworks)

Which `unittest` assertion checks that two sequences contain the same elements in the same order, using `==` semantics?

  1. assertCountEqual
  2. assertIs
  3. assertEqual Correct answer.
  4. assertIn

Explanation

`assertEqual` uses `==` and therefore compares lists element by element in order. `assertCountEqual` ignores order and compares multiset contents. `assertIs` checks identity, not equality.

Question 16Testing principles and techniques (unittest and pytest frameworks)

In pytest, what is the effect of marking a test with `@pytest.mark.xfail(strict=True)` when the test unexpectedly passes?

  1. The test is reported as xpassed and the run succeeds
  2. The test is skipped with a warning
  3. The marker is ignored
  4. The run is reported as a failure Correct answer.

Explanation

With `strict=True`, an xfail test that passes becomes a failure, signaling that the expected bug is fixed and the marker should be removed. Without strict mode, an unexpected pass is reported as XPASS but does not fail the suite. This keeps expected-failure markers honest.

Question 17Testing principles and techniques (unittest and pytest frameworks)

What is the role of a `conftest.py` file in a pytest project?

  1. It replaces `pytest.ini` for configuration
  2. It provides fixtures and hooks shared by tests in its directory and below Correct answer.
  3. It is required for every test module to be collected
  4. It declares project dependencies for installation

Explanation

`conftest.py` is loaded automatically and its fixtures, hooks, and plugins apply to tests in that directory tree. It requires no import by test modules, which makes shared setup convenient. Dependency declarations belong in packaging files instead.

Question 18Testing principles and techniques (unittest and pytest frameworks)

A test asserts `mock.assert_called_once_with(3, key='x')` and fails. Which situation would cause this failure?

  1. The mock was called twice with those arguments
  2. The mock's `side_effect` was set to `None`
  3. The mock was never configured with a `return_value`
  4. The mock was called once with `(3, key='y')` Correct answer.

Explanation

`assert_called_once_with` requires exactly one call whose arguments match exactly, including keyword names and values. A differing keyword value violates the match. Call count and argument values are both part of the assertion.

Question 19Testing principles and techniques (unittest and pytest frameworks)

Which command runs only tests marked `slow` in a pytest project?

  1. pytest -m slow Correct answer.
  2. pytest -x slow
  3. pytest -k slow
  4. pytest --slow

Explanation

`-m` selects tests by registered marker expression, so `-m slow` runs only tests decorated with `@pytest.mark.slow`. `-k` matches names and substrings rather than markers. Markers should be registered in configuration to avoid warnings.

Question 20Testing principles and techniques (unittest and pytest frameworks)

Why might a test author prefer `pytest.raises` over a bare try/except in a test?

  1. It fails the test automatically if no exception is raised and supports message matching Correct answer.
  2. It catches all exception types including `BaseException`
  3. It suppresses the exception so the test always passes
  4. It replaces the need for assertions entirely

Explanation

`pytest.raises` is an assertion: if the block completes without raising the expected exception, the test fails. It also supports `match` for message validation and exposes the exception via `excinfo`. A bare try/except would silently pass when no exception occurs.

Question 21Testing principles and techniques (unittest and pytest frameworks)

A developer writes `@pytest.fixture(autouse=True)` on a fixture in a test module. What is the effect?

  1. The fixture runs once per session
  2. Every test in that module receives the fixture without requesting it Correct answer.
  3. Only tests that name the fixture receive it
  4. The fixture is skipped unless `--autouse` is passed

Explanation

`autouse=True` makes the fixture apply to all tests within its scope of visibility, such as a module, without explicit request. It is useful for shared setup like logging configuration but can obscure dependencies. Scope is still governed by the `scope` argument.

Question 22Testing principles and techniques (unittest and pytest frameworks)

What does `unittest` do when a test method raises `unittest.SkipTest` during execution?

  1. It stops the entire test run
  2. It marks the test as an error
  3. It marks the test as skipped and continues Correct answer.
  4. It retries the test once

Explanation

Raising `SkipTest` inside a test or fixture causes that test to be reported as skipped rather than failed. This is the mechanism behind `self.skipTest()` and runtime skip decorators. The rest of the suite continues normally.

Question 23Testing principles and techniques (unittest and pytest frameworks)

A test module imports a function directly with `from app import compute` and patches `app.compute` with `unittest.mock.patch`. Why might the patch fail to affect the test?

  1. `patch` cannot be used on functions, only on classes
  2. The test references its own imported name, so patching the module attribute does not change the local binding Correct answer.
  3. `patch` only works inside `unittest.TestCase` methods
  4. The patch decorator requires `new_callable` to be set

Explanation

Patching replaces the attribute in the module where it is looked up, but `from app import compute` binds the object in the test module at import time. The code under test must resolve the name through the patched module for the substitution to take effect. Patching the name where it is used is the usual fix.

Question 24Testing principles and techniques (unittest and pytest frameworks)

Which pytest option shows the local variables of failing assertions to aid debugging?

  1. `-l` / `--showlocals` Correct answer.
  2. `-rA`
  3. `--tb=no`
  4. `-q` / `--quiet`

Explanation

`--showlocals` (or `-l`) prints local variable values in tracebacks for failing tests, which speeds diagnosis of assertion failures. `-q` reduces output, `-rA` controls the short test summary, and `--tb=no` suppresses tracebacks. These options are independent.

Question 25Testing principles and techniques (unittest and pytest frameworks)

A test uses `capsys` to capture output. Which call retrieves what was written to `sys.stdout` since the last read?

  1. `capsys.readouterr().out` Correct answer.
  2. `capsys.stdout.getvalue()`
  3. `capsys.read()`
  4. `capsys.err`

Explanation

`readouterr()` returns a named tuple with `out` and `err` containing everything captured since the previous call, and it resets the buffers. Accessing `sys.stdout` directly bypasses the capture. This pattern is standard for asserting on printed output.

Question 26Testing principles and techniques (unittest and pytest frameworks)

A test module defines a function `def test_total():` at module level, with no class. Which statement describes how pytest collects it?

  1. pytest collects it only if the function is decorated with `@pytest.mark.test`.
  2. pytest collects it only if the module also defines a class inheriting from `unittest.TestCase`.
  3. pytest collects it because the function name starts with `test_` and it is defined at module level. Correct answer.
  4. pytest collects it only if the module name starts with `test_` and the function accepts a fixture argument.

Explanation

pytest's default collection rules discover files named `test_*.py` or `*_test.py`, then collect functions whose names begin with `test_` regardless of whether a class exists. No decorator is needed, and fixture parameters are optional. The function simply runs as a test.

Question 27Testing principles and techniques (unittest and pytest frameworks)

A test class subclasses `unittest.TestCase` and defines `setUpClass` as a `@classmethod`. When does that method execute?

  1. Once after the last test method in the class finishes.
  2. Before and after every individual test method.
  3. Only when a test method raises an exception.
  4. Once before any test method in the class runs. Correct answer.

Explanation

`setUpClass` is a class-level fixture invoked once before the first test in the class executes, which makes it suitable for expensive shared setup. Per-test setup belongs in `setUp`, and teardown of the class-level resource belongs in `tearDownClass`.

Question 28Testing principles and techniques (unittest and pytest frameworks)

A pytest fixture needs to release a resource after the test that used it. Which fixture form provides teardown?

  1. A fixture decorated with `@pytest.fixture(scope='session')` and returning a context manager object.
  2. A generator fixture that yields the resource and resumes after the `yield` to clean up. Correct answer.
  3. A fixture that calls `atexit.register` with the cleanup function.
  4. A fixture that returns the resource and defines a module-level `teardown()` function.

Explanation

When a fixture uses `yield`, pytest runs the code before the `yield` as setup and the code after it as teardown once the fixture's scope ends. A plain `return` fixture has no teardown phase. `atexit` runs at interpreter exit, not at test teardown.

Question 29Testing principles and techniques (unittest and pytest frameworks)

A test calls `mock = MagicMock()` and then `mock(1, 2)`. Which assertion verifies the call arguments?

  1. `mock.assert_called_once(1, 2)`
  2. `mock.assert_called_with_args(1, 2)`
  3. `mock.assert_has_calls(1, 2)`
  4. `mock.assert_called_once_with(1, 2)` Correct answer.

Explanation

`assert_called_once_with` checks both that the mock was called exactly once and that the recorded arguments match. `assert_called_with` checks only the most recent call. The other method names shown do not exist on `Mock`.

Question 30Testing principles and techniques (unittest and pytest frameworks)

A developer wants a pytest test to be skipped at runtime when an optional C library is missing, deciding inside the test body. Which approach fits?

  1. Rename the test so it no longer starts with `test_`.
  2. Apply `@pytest.mark.skip` unconditionally to the test function.
  3. Return `False` from the test function when the import fails.
  4. Call `pytest.skip('missing lib')` inside the test when the import fails. Correct answer.

Explanation

`pytest.skip()` aborts the current test at runtime and records it as skipped with the given reason, which suits conditions only known during execution. A skip marker is evaluated before the test body runs, so it cannot inspect a runtime import result.

Question 31Testing principles and techniques (unittest and pytest frameworks)

A test needs to assert that calling a function raises `KeyError` and also inspect the exception object. Which `pytest.raises` form gives access to it?

  1. `with pytest.raises(KeyError).value as excinfo:`
  2. `with pytest.raises(KeyError, excinfo):` then read `excinfo`.
  3. `with pytest.raises(KeyError) as excinfo:` then read `excinfo.value`. Correct answer.
  4. `with pytest.raises(KeyError) as excinfo:` then read `excinfo.type`.

Explanation

`pytest.raises` returns an `ExceptionInfo` object through the `as` target, and its `.value` attribute holds the caught exception instance. `.type` holds the exception class, not the instance. The other syntaxes are invalid.

Question 32Testing principles and techniques (unittest and pytest frameworks)

A test needs a value that is expensive to build and should be shared by every test in a module but rebuilt for each module. Which fixture scope is appropriate?

  1. `scope='function'`
  2. `scope='session'`
  3. `scope='module'` Correct answer.
  4. `scope='class'`

Explanation

Module scope creates the fixture once per test module and tears it down when that module finishes, matching the requirement exactly. Function scope would rebuild per test, session scope would share across the whole run, and class scope would rebuild per class.

Question 33Testing principles and techniques (unittest and pytest frameworks)

A test needs to verify that a function calls a collaborator with a dictionary argument whose key order may vary. Which mock assertion handles this?

  1. `mock.assert_called_once_with(['a', 1, 'b', 2])`
  2. `mock.assert_called_once_with({'a': 1, 'b': 2})` Correct answer.
  3. `mock.assert_called_once_with(sorted({'a': 1, 'b': 2}))`
  4. `mock.assert_called_once_with("{'a': 1, 'b': 2}")`

Explanation

Mock call comparison uses `==`, and dictionary equality ignores insertion order, so passing the expected dict directly works regardless of key order. String, list, and sorted-key representations are different objects and will not compare equal to the dict.

Question 34Testing principles and techniques (unittest and pytest frameworks)

A developer runs `pytest -k 'login and not slow'`. Which tests execute?

  1. Tests whose node ID matches `login` and does not match `slow`. Correct answer.
  2. Tests that call the fixtures named `login` and `slow`.
  3. Only tests in a file named `login.py` that lack the `slow` marker.
  4. Tests whose docstring contains both words.

Explanation

The `-k` expression filters by substring match against test names and node IDs, and supports boolean operators including `and` and `not`. It does not inspect marker names, fixture names, or docstrings.

Question 35Testing principles and techniques (unittest and pytest frameworks)

A test uses `@pytest.mark.parametrize('n,expected', [(2, 4), (3, 9)])`. How many test items does pytest report for that function?

  1. One, because the function is defined once.
  2. Zero until the marker is registered in `pytest.ini`.
  3. Two, one per parameter set, each reported with its own ID. Correct answer.
  4. Four, because each argument is counted separately.

Explanation

`parametrize` expands a single function into one test item per parameter set, and pytest generates distinct IDs for each so failures are attributable. Unregistered markers only produce a warning, not zero collection.

Question 36Testing principles and techniques (unittest and pytest frameworks)

A test patches a module-level constant with `unittest.mock.patch('app.config.DEBUG', True)` used as a context manager. What happens when the `with` block exits?

  1. The patched value persists until the interpreter exits.
  2. The attribute is deleted from `app.config`.
  3. The original value of `app.config.DEBUG` is restored automatically. Correct answer.
  4. The patch applies only to the first call inside the block.

Explanation

When `patch` is used as a context manager, it saves the original attribute on entry and restores it on exit, even if the block raises. This isolation prevents state leaking between tests.

Question 37Testing principles and techniques (unittest and pytest frameworks)

A test asserts on a list of results and fails with a diff. Which pytest feature produces the detailed comparison of differing elements?

  1. Assertion rewriting, which pytest enables automatically for test modules. Correct answer.
  2. The `--tb=no` command-line option.
  3. The `pytest.approx` helper.
  4. The `capfd` fixture.

Explanation

pytest rewrites assertions in test modules so that a failing `assert` reports the intermediate values and a diff of compared sequences. `--tb=no` suppresses tracebacks, `capfd` captures file descriptors, and `approx` handles floats.

Question 38Testing principles and techniques (unittest and pytest frameworks)

A test module contains both a `conftest.py` fixture named `db` at the project root and a fixture named `db` in the test module. A test in that module requests `db`. Which fixture is used?

  1. The one defined in the test module, because closer definitions override outer ones. Correct answer.
  2. Both run, and their results are merged.
  3. The root `conftest.py` one, because it is discovered first.
  4. pytest raises an error for the duplicate fixture name.

Explanation

pytest resolves fixtures by searching from the test's own module outward, so a local definition shadows a same-named fixture from a higher-level `conftest.py`. There is no merge and no error for the shadowing case.

Question 39Testing principles and techniques (unittest and pytest frameworks)

A test class subclasses `unittest.TestCase` and defines `tearDown`. When does it run?

  1. Before each test method, before `setUp`.
  2. Only when the test method passes.
  3. After each test method, even when the test method fails. Correct answer.
  4. Only after the final test method in the class.

Explanation

`tearDown` runs after every test method in the class and executes even if the test failed, which is why cleanup belongs there. Class-level final cleanup is the role of `tearDownClass`.

Question 40Testing principles and techniques (unittest and pytest frameworks)

A test uses `monkeypatch.setattr('app.time.time', fake_time)` where `app.time` is the standard `time` module. Why can this leak into other tests?

  1. The patch is applied at import time and cannot be reverted.
  2. `monkeypatch.setattr` only supports string targets, so the call has no effect.
  3. The patch modifies the shared `time` module object, and monkeypatch only undoes it if the fixture is used by that test. Correct answer.
  4. `monkeypatch` restores attributes only for `os.environ`, not for modules.

Explanation

`monkeypatch.setattr` with a dotted string resolves to the real `time` module and mutates it globally; the `monkeypatch` fixture reverts it at the end of the requesting test. If other tests run concurrently or the patch escapes the fixture lifecycle, the change is visible elsewhere. Patching `app.time` as an imported name, or using a scoped mock, limits the blast radius.

Question 41Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

Which statement best describes the intent of the Singleton pattern?

  1. Define a one-to-many dependency so that dependents are notified of changes
  2. Attach additional responsibilities to an object dynamically at runtime
  3. Ensure a class has only one instance and provide a global point of access to it Correct answer.
  4. Create families of related objects without specifying their concrete classes

Explanation

Singleton restricts instantiation to a single object and exposes it through a controlled access point, typically a static method or module-level instance. The other options describe Abstract Factory, Decorator, and Observer respectively.

Question 42Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

In Python, which mechanism most directly guarantees that a module-level object is created exactly once per interpreter process?

  1. Wrapping the constructor in a try/except block
  2. Overriding __del__ to prevent garbage collection
  3. Using a class attribute initialized to None and reassigned in __init__
  4. Defining the object at module scope so the import system caches the module Correct answer.

Explanation

Python caches imported modules in sys.modules, so module-level code runs only on the first import; subsequent imports return the same module object and therefore the same instance. Constructor guards and __del__ overrides do not provide this guarantee.

Question 43Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

A class implements __new__ to return a cached instance and defines __init__ normally. What happens each time the class is called after the first time?

  1. A new instance is created and the cached one is discarded
  2. __init__ is skipped because the instance already exists
  3. A TypeError is raised because __init__ cannot run twice
  4. __init__ runs again on the cached instance with the new arguments Correct answer.

Explanation

Python calls __new__, then calls __init__ on whatever object __new__ returns, provided it is an instance of the class. Returning a cached instance therefore re-runs __init__ with the new arguments unless the class guards against it.

Question 44Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

Which design problem is the Factory Method pattern primarily intended to solve?

  1. Encapsulating a request as an object so it can be queued or undone
  2. Letting subclasses decide which concrete product class to instantiate Correct answer.
  3. Ensuring only one instance of a class exists in the process
  4. Converting an incompatible interface into one a client expects

Explanation

Factory Method defers instantiation to subclasses by declaring a creation method that subclasses override to return specific products. This decouples client code from concrete product classes.

Question 45Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

A module exposes a single function create_parser(kind) that returns one of several parser classes based on a string argument. Which pattern does this most closely represent?

  1. Abstract Factory, because it produces families of related objects
  2. Prototype, because instances are cloned from prototypes
  3. Builder, because construction happens step by step
  4. Simple factory (a factory function) rather than the full Factory Method pattern Correct answer.

Explanation

A single function that selects and returns a concrete class based on an argument is commonly called a simple factory or factory function. It centralizes creation but lacks the subclass-driven polymorphism of Factory Method.

Question 46Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

In the classic Factory Method structure, what role does the creator class play?

  1. It declares the factory method returning a product interface and may use it in its own operations Correct answer.
  2. It directly instantiates each concrete product inside client code
  3. It enforces a single shared product instance across the application
  4. It stores every product ever created in a registry for later reuse

Explanation

The creator declares the factory method with a product-typed return value and often contains logic that relies on the product without knowing its concrete class. Concrete creators override the method to return specific products.

Question 47Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

What is the primary purpose of the Facade pattern?

  1. Provide a simplified, unified interface to a set of interfaces in a subsystem Correct answer.
  2. Notify dependents automatically when an object changes state
  3. Guarantee that a subsystem has exactly one entry point object
  4. Control access to an object by interposing a surrogate

Explanation

A facade wraps a complex subsystem behind a higher-level interface that is easier for clients to use, without removing the subsystem's lower-level access. It simplifies usage rather than restricting it.

Question 48Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

How does a Facade differ from an Adapter?

  1. A facade converts interfaces, while an adapter simplifies a subsystem
  2. A facade simplifies access to a subsystem, while an adapter converts one interface into another expected by a client Correct answer.
  3. A facade adds behavior at runtime, while an adapter removes behavior
  4. A facade is always a Singleton, while an adapter is always a Proxy

Explanation

Facade reduces complexity by presenting a convenient interface over multiple subsystem classes. Adapter exists to make an existing interface usable by a client that expects a different one.

Question 49Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

A facade method internally calls three subsystem objects in sequence. Which statement about client coupling is accurate?

  1. Clients no longer depend on the subsystem at all, and the subsystem becomes unreachable to them
  2. Clients depend on the facade's interface, but the facade still depends on the subsystem classes Correct answer.
  3. The subsystem classes must be modified to inherit from the facade
  4. The facade eliminates the need for the subsystem classes to exist

Explanation

The facade hides complexity from clients but remains coupled to the subsystem it orchestrates. Clients that only use the facade avoid direct subsystem dependencies, yet the subsystem remains available and unchanged.

Question 50Design patterns (OOP design principles; Singleton, Factory, Facade, Proxy, Observer, Command, Template Method, and State)

Which pattern is defined as a surrogate or placeholder that controls access to another object?

  1. Command
  2. Proxy Correct answer.
  3. Template Method
  4. Observer

Explanation

Proxy provides a stand-in object with the same interface as the real subject, adding control such as lazy creation, access checks, or remote communication. The client interacts with the proxy as if it were the real object.