PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium
Question 36
You are experimenting with Python's type metaclass to understand its role in class creation. You want to define a custom metaclass CustomMeta that modifies the name of any class that uses it, by prefixing "Modified_" to the class name. You use the type.__new__ method to achieve this.
- class CustomMeta(type):
- def __new__(cls, name, bases, attrs):
- name = "Modified_" + name
- return super().__new__(cls, name, bases, attrs)
- # Scenario: Define a class with the custom metaclass
- class MyClass(metaclass=CustomMeta):
- def method(self):
- return "This is MyClass."
- # Instantiate and check the class name and method output
- obj = MyClass()
- print(type(obj).__name__)
- print(obj.method())
What will be the output of the code?
-
A
- MyClass
- This is Modified_MyClass.
-
B
- MyClass
- This is MyClass.
-
C
- Modified_MyClass
- This is MyClass.
-
D
- Modified_MyClass
- This is Modified_MyClass.
Reveal correct answer
Correct answer: C
A.
This is incorrect. The class name is changed to "Modified_MyClass", but the method's return value does not depend on the class name; it remains "This is MyClass." The combination of outputs in this answer does not match the actual behavior of the code.
B.
This is incorrect. The custom metaclass changes the class name to "Modified_MyClass", so type(obj).__name__ would not return "MyClass". The method output is correct, but the class name output is not.
C.
This is the correct answer. The CustomMeta metaclass modifies the class name by prefixing "Modified_" to it during the class creation process. Thus, MyClass is actually named Modified_MyClass internally. The method method() still returns "This is MyClass." as defined in the original class body.
D.
This is incorrect. While the class name is modified by the metaclass, the method method() is not affected by the metaclass and will return the string defined within it, which is "This is MyClass." The output of the method does not reflect the name change.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
