PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Hard
Question 27
Consider the following Python code:
- class Meta(type):
- def __new__(mcs, name, bases, attrs):
- attrs['custom_attr'] = 42
- return super().__new__(mcs, name, bases, attrs)
- class MyClass(metaclass=Meta):
- pass
Which of the following statements is true?
-
A
An instance of
MyClasshas an attribute namedcustom_attr. -
B
MyClass.custom_attrreturnsNone. -
C
MyClass.custom_attrreturns42. -
D
MyClass.custom_attrraises anAttributeError.
Reveal correct answer
Correct answer: C
A.
While MyClass has a class attribute named custom_attr, instances of MyClass do not automatically have an instance attribute named custom_attr. If you create an instance of MyClass and try to access custom_attr, it will return the class attribute custom_attr, unless an instance attribute custom_attr has been set.
B.
MyClass.custom_attr does not return None. The metaclass Meta adds a class attribute named custom_attr with the value 42 during the creation of MyClass.
C.
The metaclass Meta adds a class attribute named custom_attr with the value 42 during the creation of MyClass. Therefore, MyClass.custom_attr returns 42.
D.
MyClass.custom_attr does not raise an AttributeError. The metaclass Meta adds a class attribute named custom_attr during the creation of MyClass.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
