Bird
0
0

Consider this class:

hard📝 Application Q9 of 15
Python - Constructors and Object Initialization
Consider this class:
class Gadget:
    def __init__(self, name='Gizmo', features=None):
        if features is None:
            features = ['Bluetooth', 'WiFi']
        self.name = name
        self.features = features

g1 = Gadget()
g2 = Gadget(features=['GPS'])
print(g1.features, g2.features)

What is the output?
A['Bluetooth', 'WiFi'] ['Bluetooth', 'WiFi']
BNone ['GPS']
C['Bluetooth', 'WiFi'] ['GPS']
DError: Default mutable argument
Step-by-Step Solution
Solution:
  1. Step 1: Understand default mutable argument handling

    features default is None, so inside constructor it is replaced with a new list to avoid shared mutable default.
  2. Step 2: Analyze object creations and prints

    g1 uses default features list ['Bluetooth', 'WiFi'], g2 uses provided ['GPS']. Printing shows these lists.
  3. Final Answer:

    ['Bluetooth', 'WiFi'] ['GPS'] -> Option C
  4. Quick Check:

    Use None to avoid mutable default bugs [OK]
Quick Trick: Use None as default for mutable types [OK]
Common Mistakes:
  • Using mutable defaults directly
  • Expecting shared list between instances
  • Confusing None with empty list

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes