PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium
Question 23
What is the result of the following code?
- import json
- class Vector:
- def __init__(self, *components):
- self.components = components
- def __repr__(self):
- return f'Vector{self.components}'
- def __str__(self):
- return f'{self.components}'
- class VectorEncoder(json.JSONEncoder):
- def default(self, v):
- if isinstance(v, Vector):
- return v.__dict__
- else:
- return super().default(self, v)
- v1 = Vector(4, 2, 6)
- print(json.dumps(v1, cls=VectorEncoder))
-
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
TypeErrorexception. Object of typeVectoris 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.
