PCPP-32-101

Free PCPP-32-101 practice questions

10 questions from our PCPP-32-101 practice tests, each with the correct answer and a written explanation. Read them with the answers shown, or switch to quiz mode and answer first.

Back to the PCPP-32-101 practice exams

Question 1 of 10, Advanced Object-Oriented Programming

A subclass of str customizes object creation: class Upper(str): def __new__(cls, value): return super().__new__(cls, value.upper()) def __init__(self, value): self.original = value u = Upper('abc') print(u, u.original, isinstance(u, str), u + 'd') What is printed?

  1. AABC abc False ABCd
  2. BABC abc True ABCd Correct answer
  3. CABC None True ABCd
  4. DTypeError raised by __init__()

Answer and explanation: str is immutable, so its value must be chosen in __new__, which here creates the string from value.upper(). __init__ then receives the same original argument and stores it unchanged in an instance attribute; overriding __init__ with an extra parameter is allowed because __new__ already consumed the value. Concatenation uses str.__add__, which returns a plain str built from the uppercase value and 'd', and an instance of a str subclass still passes isinstance(u, str).

Question 2 of 10, Advanced Object-Oriented Programming

A decorator factory is applied to a function: def repeat(n): def deco(f): def wrapper(*args, **kwargs): return [f(*args, **kwargs) for _ in range(n)] return wrapper return deco @repeat(3) def greet(x): return x.upper() print(greet('hi'), greet.__name__) What is printed?

  1. A['HI', 'HI', 'HI'] deco
  2. B['HI', 'HI', 'HI'] greet
  3. C['HI', 'HI', 'HI'] wrapper Correct answer
  4. D['HI'] wrapper

Answer and explanation: repeat(3) returns deco, deco(greet) returns wrapper, so the name greet is bound to wrapper, which returns a list of three results. Because functools.wraps was not used, the __name__ of the decorated object is 'wrapper', not 'greet'. 'deco' is the name of the intermediate decorator that is discarded after decoration, and n=3 makes the list comprehension call the original function three times, not once.

Question 3 of 10, Advanced Object-Oriented Programming

A base class registers its subclasses: class Plugin: registry = {} def __init_subclass__(cls, key=None, kwargs): super().__init_subclass__(kwargs) Plugin.registry[key or cls.__name__.lower()] = cls class Csv(Plugin, key='csv'): pass class Json(Plugin): pass print(sorted(Plugin.registry), 'plugin' in Plugin.registry) What is printed?

  1. A['csv', 'json'] False Correct answer
  2. B[] False
  3. C['csv'] False
  4. D['csv', 'json', 'plugin'] True

Answer and explanation: __init_subclass__ runs each time a subclass is created, receiving extra keyword arguments from the class statement, so Csv registers under 'csv' and Json under its lowercased name. It does not run for the class that defines it, so Plugin itself is not registered. Json is registered too, because key defaults to None and the class name is used. Registration happens at class creation, without any instance being made.

Question 4 of 10, Advanced Object-Oriented Programming

Consider the following class hierarchy: class A: def who(self): return 'A' class B(A): def who(self): return 'B' + super().who() class C(A): def who(self): return 'C' + super().who() class D(B, C): def who(self): return 'D' + super().who() print(D().who(), [k.__name__ for k in D.__mro__]) What is the output?

  1. ADBCA ['D', 'B', 'C', 'A', 'object'] Correct answer
  2. BDBACA ['D', 'B', 'A', 'C', 'object']
  3. CDBA ['D', 'B', 'A', 'C', 'object']
  4. DDCBA ['D', 'C', 'B', 'A', 'object']

Answer and explanation: Python linearizes the diamond with C3, giving the MRO D, B, C, A, object, and each super().who() call moves to the next class in that order, so the chain builds 'DBCA'. A depth-first order (D, B, A, C) is what classic old-style classes used and would visit A before C. Listing C before B ignores the left-to-right order of the bases, and A is never visited twice because C3 keeps each class only once.

Question 5 of 10, Coding Conventions, Best Practices, and Standardization

A long arithmetic expression must be split over several lines. Following the current PEP 8 recommendation for new code, where should the lines break relative to binary operators such as + and -?

  1. AAfter each binary operator, so every broken line ends with the operator
  2. BOnly after commas, because PEP 8 forbids breaking a line next to any binary operator
  3. CEither way, as long as each operator also gets its own line with no operands
  4. DBefore each binary operator, so every continued line starts with the operator Correct answer

Answer and explanation: PEP 8 recommends breaking before binary operators in new code, following Knuth's style, because the operators then line up with their operands and the expression is easier to read. Breaking after operators is still allowed for consistency with existing code, but it is not the recommendation, and PEP 8 does not forbid operator breaks or require operators on lines of their own.

Question 6 of 10, GUI Programming

A tkinter developer places one Label in a Frame with pack() and a second Label in the same Frame with grid(). The application freezes or raises a TclError. What is the recommended fix?

  1. AUse only one geometry manager for all widgets that share the same master Correct answer
  2. BGive the gridded Label a higher row number so pack() can place the other Label
  3. CCall update_idletasks() between the calls so that both managers can share it
  4. DCall grid() before pack() so that the grid manager takes priority in the Frame

Answer and explanation: pack() and grid() both try to control the size of their shared master, and when used for siblings in the same container they can fight endlessly; recent Tk versions detect this and raise a TclError. The fix is to use one manager per container, nesting Frames if different layouts are needed. Changing call order, forcing idle updates or choosing row numbers does not stop the two managers from conflicting.

Question 7 of 10, GUI Programming. Choose 2.

A trainee asks how event-driven GUI programs differ from simple scripts. Which two statements are correct for tkinter applications? (Choose two.)

  1. AHandlers run in the order in which the widgets were created, regardless of the events
  2. BThe event loop dispatches events such as clicks, key presses and timers to the bound handlers Correct answer
  3. CWidgets can be updated safely from any thread without any coordination with the loop
  4. DHandlers should return quickly and split long work into after() steps or worker threads Correct answer
  5. EThe program polls each widget in its own loop to find out whether it has been clicked

Answer and explanation: In event-driven programs the event loop waits for events and calls the matching handlers, so the program flow follows user actions. A slow handler blocks that loop, so long tasks are split or moved to threads that hand results back. Applications do not poll widgets themselves, handlers run when their events occur, and tkinter is not safe to update freely from other threads.

Question 8 of 10, Network Programming

A dictionary is serialized before being sent to a REST service: import json print(json.dumps({'a': None, 'b': (1, 2), 3: True})) What is the output?

  1. A{"a": null, "b": {"0": 1, "1": 2}, "3": true}
  2. BTypeError: keys must be str, int, float, bool or None
  3. C{"a": null, "b": [1, 2], "3": true} Correct answer
  4. D{"a": None, "b": [1, 2], "3": True}

Answer and explanation: json.dumps() converts None to null, True to true and tuples to JSON arrays, and it converts integer keys to strings because JSON object keys are always strings. Python literals such as None and True are not valid JSON. A tuple is encoded as an array, not as an object keyed by index, and the TypeError about keys is raised only for key types such as tuples, not for ints.

Question 9 of 10, Network Programming

A client sends 'GET / HTTP/1.1' with a Host header over a raw socket and then reads with a loop that stops when recv() returns b''. The full page arrives, but the loop never ends. What is the most likely fix?

  1. ACall sock.listen() after sending, so the client is notified when the response is done
  2. BIncrease the recv() buffer to 64 KB, so the whole response arrives in one single call
  3. CSend the request as a str instead of bytes, so the server knows where the request ends
  4. DAdd a Connection: close header, so the server closes the connection after its response Correct answer

Answer and explanation: HTTP/1.1 connections are persistent by default, so the server keeps the socket open after responding and recv() blocks instead of returning b''. Requesting Connection: close makes the server close the connection, which ends the loop. Sockets only accept bytes, listen() is a server call, and a larger buffer does not change when the peer closes the stream.

Question 10 of 10, File Processing and Communicating with a Program's Environment

A setup script creates a table with CREATE TABLE products(...). It works the first time, but running it again stops with sqlite3.OperationalError: table products already exists. Which change lets the script run repeatedly while keeping existing data?

  1. AOpen the connection with sqlite3.connect('shop.db', uri=True)
  2. BCall con.rollback() before executing the CREATE TABLE statement
  3. CRun DROP TABLE products before every CREATE TABLE statement
  4. DUse CREATE TABLE IF NOT EXISTS products(...) in the setup script Correct answer

Answer and explanation: IF NOT EXISTS makes the statement a no-op when the table is already present, so existing rows stay intact. Dropping the table first also avoids the error but deletes all data every run. The uri flag only changes how the database name is parsed, and rolling back does not remove a table that was already committed.