Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Python - Classes and Object Lifecycle
What will be the output of this code?
class Dog:
    species = "Canine"

dog1 = Dog()
dog2 = Dog()
Dog.species = "Wolf"
print(dog1.species)
print(dog2.species)
ACanine\nCanine
BWolf\nCanine
CWolf\nWolf
DCanine\nWolf
Step-by-Step Solution
Solution:
  1. Step 1: Understand class attribute change

    The attribute species is a class attribute shared by all instances.
  2. Step 2: Effect of changing class attribute

    Changing Dog.species to "Wolf" updates the value for all instances that don't have their own species attribute.
  3. Final Answer:

    Wolf\nWolf -> Option C
  4. Quick Check:

    Changing class attribute affects all instances [OK]
Quick Trick: Changing class attribute changes it for all instances without override [OK]
Common Mistakes:
  • Thinking instances keep old class attribute values
  • Confusing instance and class attributes
  • Expecting different outputs for dog1 and dog2

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes