LearnFrenzy
Sign in Take a free test

OOP in Python · Predict the Output · Question 5

Counting instances with a class attribute Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following Python program?

main.py
class User:
    count = 0
    def __init__(self, name):
        self.name = name
        User.count += 1
        self.id = User.count

users = [User(n) for n in ["Asha", "Ravi", "Meera"]]
print(User.count, users[1].id, users[2].count)
  • A 3 1 3
  • B 3 2 3 Correct
  • C 1 1 1
  • D 3 2 1
Correct Answer: Option B

The shared counter goes up with each object; Ravi was second. users[2].count reads the class attribute.

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