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

Question 16

You are developing a Python application that involves handling different types of vehicles. You have the following class hierarchy:



You need to check the types of various objects at runtime to ensure that your program handles them correctly. Consider the following code:



Which of the following statements about this code is correct?

  • A

    The function check_vehicle will always return "This is a generic Vehicle." when an object of ElectricCar is passed.

  • B

    The function check_vehicle will raise a TypeError if an object of an unrecognized class (i.e., not a subclass of Vehicle) is passed.

  • C

    The function check_vehicle can potentially return "This is a Car." when an object of ElectricCar is passed.

  • D

    The function check_vehicle will always return "This is an ElectricCar." when an object of ElectricCar is passed.

Reveal correct answer

Correct answer: D

A.

This answer is incorrect because isinstance(vehicle, ElectricCar) will return True if the object passed is an instance of ElectricCar, and since this is the first condition checked, the function will always return "This is an ElectricCar." when an ElectricCar object is passed.

B.

This answer is incorrect because the isinstance() function does not raise a TypeError when the object does not match any type; it simply returns False. Therefore, the function will execute the else block and return "Unknown vehicle type" instead of raising an error.

C.

This answer is incorrect because, while ElectricCar is indeed a subclass of Car, the isinstance(vehicle, ElectricCar) check happens before isinstance(vehicle, Car) in the code. Therefore, if the object is an instance of ElectricCar, the first condition will catch it, and the function will return "This is an ElectricCar." The code will not reach the isinstance(vehicle, Car) check.

D.

This answer is correct because isinstance(vehicle, ElectricCar) will return True if the object passed is an instance of ElectricCar, and since this is the first condition checked, the function will always return "This is an ElectricCar." when an ElectricCar object is passed.

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