Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q4 of Q15
Python - Classes and Object Lifecycle
What will be the output of this code?
class Cat:
    legs = 4

c1 = Cat()
c2 = Cat()
c1.legs = 3
print(Cat.legs, c1.legs, c2.legs)
A3 3 3
B4 3 4
C4 4 4
D3 4 3
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute assignment

    Assigning c1.legs = 3 creates an instance attribute for c1, shadowing the class attribute.
  2. Step 2: Determine values printed

    Cat.legs remains 4, c1.legs is 3 (instance attribute), c2.legs uses class attribute 4.
  3. Final Answer:

    4 3 4 -> Option B
  4. Quick Check:

    Instance attribute shadows class attribute [OK]
Quick Trick: Instance attribute overrides class attribute for that object [OK]
Common Mistakes:
MISTAKES
  • Assuming class attribute changes for all instances
  • Confusing instance and class attribute access
  • Expecting all to print 3

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes