LearnFrenzy
Sign in Take a free test

OOP in Python · Predict the Output · Question 2

Shadowing a class attribute Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following Python program?

main.py
class Dog:
    species = "canine"

d1, d2 = Dog(), Dog()
d1.species = "wolf"
print(d1.species, d2.species, Dog.species)
Dog.species = "dog"
print(d1.species, d2.species)
  • A wolf wolf wolf dog dog
  • B wolf canine canine dog dog
  • C wolf canine wolf wolf dog
  • D wolf canine canine wolf dog Correct
Correct Answer: Option D

d1 has its own species attribute; d2 still reads the class attribute, so changing Dog.species affects only d2.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links