PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Hard
Question 6
Consider the following Python code snippet:
- class Meta(type):
- def __new__(cls, name, bases, attrs):
- new_class = super().__new__(cls, name, bases, attrs)
- new_class.instances = 0
- original_init = new_class.__init__
- def new_init(self, *args, **kwargs):
- new_class.instances += 1
- original_init(self, *args, **kwargs)
- new_class.__init__ = new_init
- return new_class
- class MyClass(metaclass=Meta):
- pass
- a = MyClass()
- b = MyClass()
- c = MyClass()
What will be the output of print(MyClass.instances)?
-
A
3 -
B
1 -
C
0 -
D
An
AttributeErrorwill be raised.
Reveal correct answer
Correct answer: A
A.
The instances attribute is incremented each time an instance of MyClass is created. Since MyClass is instantiated three times, MyClass.instances will be 3.
B.
While MyClass.instances would be 1 after the first instance of MyClass is created, it will be incremented two more times when the second and third instances are created, so the final value will be 3, not 1.
C.
The instances attribute is incremented each time an instance of MyClass is created. Since MyClass is instantiated three times, MyClass.instances will be 3, not 0.
D.
The instances attribute is created in the Meta metaclass and assigned to the class during its creation, so accessing MyClass.instances will not raise an AttributeError.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
