Challenge - 5 Problems
Instance Attribute Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of instance attribute modification
What is the output of this Python code involving instance attributes?
Python
class Dog: def __init__(self, name): self.name = name d1 = Dog('Buddy') d2 = Dog('Max') d1.name = 'Charlie' print(d2.name)
Attempts:
2 left
💡 Hint
Each instance has its own attributes. Changing one does not affect the other.
✗ Incorrect
Changing d1.name only changes the name for d1. d2.name remains 'Max'.
❓ Predict Output
intermediate2:00remaining
Instance attribute shadowing class attribute
What will be printed by this code?
Python
class Cat: species = 'Felis' def __init__(self, name): self.name = name c = Cat('Whiskers') c.species = 'Panthera' print(Cat.species) print(c.species)
Attempts:
2 left
💡 Hint
Instance attribute with the same name hides the class attribute for that instance.
✗ Incorrect
Class attribute Cat.species remains 'Felis'. Instance c.species is set to 'Panthera', shadowing the class attribute.
🔧 Debug
advanced2:00remaining
Identify the error in instance attribute assignment
What error does this code raise when run?
Python
class Person: def __init__(self, name): name = name p = Person('Alice') print(p.name)
Attempts:
2 left
💡 Hint
Check if the instance attribute is properly assigned inside __init__.
✗ Incorrect
The code assigns to local variable 'name' instead of instance attribute 'self.name'. So p has no 'name' attribute, causing AttributeError.
❓ Predict Output
advanced2:00remaining
Instance attribute default value behavior
What is the output of this code?
Python
class Counter: def __init__(self): if not hasattr(self, 'count'): self.count = 0 def increment(self): self.count += 1 c1 = Counter() c2 = Counter() c1.increment() c1.increment() c2.increment() print(c1.count, c2.count)
Attempts:
2 left
💡 Hint
Each instance has its own 'count' attribute initialized to 0.
✗ Incorrect
c1 increments twice, so c1.count is 2. c2 increments once, so c2.count is 1.
🧠 Conceptual
expert2:00remaining
Understanding instance attribute creation timing
When is an instance attribute created in Python classes?
Attempts:
2 left
💡 Hint
Think about when the attribute actually appears on the object.
✗ Incorrect
Instance attributes are created when assigned to self inside methods or after instance creation, not before.