PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium

Question 23

What is the result of the following code?



  • A

    This code will output {"components": [4, 2, 6]} to the console.

  • B

    This code will output Vector(4, 2, 6) to the console.

  • C

    This code will output (4, 2, 6) to the console.

  • D

    This code will raise the TypeError exception. Object of type Vector is not JSON serializable.

Reveal correct answer

Correct answer: A

A.

This is the correct answer. The json.dumps() function serializes the v1 object to a JSON string. The VectorEncoder class overrides the default method of json.JSONEncoder to handle the serialization of Vector objects. It converts the Vector object into its __dict__ representation, which is {"components": (4, 2, 6)}. In JSON format, tuples are serialized as lists, so the output is {"components": [4, 2, 6]}.

B.

This is incorrect. This output corresponds to the __repr__ method of the Vector class, which is not invoked here. The json.dumps() function, combined with the VectorEncoder, produces a JSON string, not the representation of the object.

C.

This is incorrect. This would be the output if you directly printed the string representation of the Vector object (print(str(v1))). However, json.dumps() is used here with a custom encoder, so the output is a JSON string, not the tuple itself.

D.

This is incorrect. Normally, trying to serialize a Vector object would raise a TypeError, but the custom VectorEncoder class properly handles the serialization, so no exception is raised.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need