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

Question 10

You are developing a Python application that involves tracking instances of a Vehicle class. To ensure that every time a new vehicle is created, it gets a unique identifier, you decide to implement a class method that increments a class-level counter and assigns this value to each new vehicle. The class method uses the cls parameter to achieve this. Here is the implementation:



What will be the value of Vehicle._counter after creating three instances of the Vehicle class?

  • A

    1

  • B

    2

  • C

    3

  • D

    0

Reveal correct answer

Correct answer: C

A.

This answer might be chosen if one mistakenly assumes that the counter is reset or only incremented for the first instance, which is not the case.

B.

This could be chosen if someone mistakenly assumes that the counter is only incremented when cls._counter is accessed the second time.

C.

The _generate_id class method is called for each instance creation. Since the cls parameter refers to the class itself, cls._counter is incremented each time a new Vehicle is instantiated. Therefore, after three instances, the counter will have been incremented three times, resulting in Vehicle._counter being 3.

D.

This could be chosen if someone mistakenly believes that the _counter attribute is never incremented or that the class method is not working correctly.

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