Examveda

What is the output of the following code:
class MyClass:
count = 0
def init(self):
MyClass.count += 1
obj1 = MyClass()
obj2 = MyClass()
print(obj1.count)

A. 2

B. 1

C. An error will occur

D. 0

Answer: Option D

Solution (By Examveda Team)

Let's break down this Python code step-by-step:

First, we have a class called `MyClass`:
This is like a blueprint for creating objects.

Inside the class, we have `count = 0`:
This is a class variable called `count`.
It's shared by all instances (objects) of the `MyClass`.
Initially, it's set to 0.

Next, we have `def __init__(self):`:
This is the constructor (initializer) of the class.
It's automatically called when you create a new object of the class.

Inside the constructor, we have `MyClass.count += 1`:
This line increments the `count` class variable by 1 every time a new object is created.
`MyClass.count` ensures we're updating the class variable, not an instance variable.

Now, let's look at the object creation:
`obj1 = MyClass()`
This creates the first object of the class. The `__init__` method is called, and `MyClass.count` becomes 1.

`obj2 = MyClass()`
This creates the second object of the class. The `__init__` method is called again, and `MyClass.count` becomes 2.

Finally, we have `print(obj1.count)`:
This prints the value of the `count` variable.
Since `count` is a class variable, `obj1.count` will access the class variable which is currently equal to 2.

Therefore, the output is 2.

So, the correct answer is Option A: 2

This Question Belongs to Python Program >> Classes And Objects In Python

Join The Discussion

Comments (1)

  1. Kainaat Yousaf
    Kainaat Yousaf:
    3 months ago

    Its answer should be zero.

Related Questions on Classes and Objects in Python