Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Python - Class Methods and Static Methods
What will be the output of this code?
class Example:
    count = 0

    def __init__(self):
        Example.count += 1

    @classmethod
    def get_count(cls):
        return cls.count

obj1 = Example()
obj2 = Example()
print(Example.get_count())
A2
B0
C1
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand the constructor behavior

    Each time an Example object is created, the class variable 'count' increases by 1. Two objects are created, so count becomes 2.
  2. Step 2: Understand the class method output

    The class method 'get_count' returns the current value of 'count', which is 2 after creating two objects.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Class variable incremented twice = 2 [OK]
Quick Trick: Class methods access shared data like 'count' [OK]
Common Mistakes:
  • Thinking count resets per instance
  • Confusing instance and class variables
  • Expecting an error due to method call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes