Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Python - Classes and Object Lifecycle
What will be the output of this code?
class Bird:
    sound = "tweet"

b1 = Bird()
b2 = Bird()
Bird.sound = "chirp"
print(b1.sound, b2.sound)
Atweet tweet
Bchirp chirp
Ctweet chirp
Dchirp tweet
Step-by-Step Solution
Solution:
  1. Step 1: Understand class attribute change

    Changing Bird.sound updates the class attribute for all instances that don't have an instance attribute.
  2. Step 2: Check instance attributes

    Neither b1 nor b2 has an instance attribute sound, so both use updated class attribute "chirp".
  3. Final Answer:

    chirp chirp -> Option B
  4. Quick Check:

    Class attribute change affects all instances without override [OK]
Quick Trick: Changing class attribute affects all instances without instance override [OK]
Common Mistakes:
  • Thinking instances keep old value
  • Confusing instance and class attributes
  • Expecting mixed outputs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes