Knowee
Questions
Features
Study Tools

What will be the output of the following code?class MyClass:    class_variable = 10    def __init__(self, instance_variable):        self.instance_variable = instance_variableobj1 = MyClass(20)obj2 = MyClass(30)MyClass.class_variable = 40print(obj1.class_variable, obj2.class_variable)10 10 20 3040 4020 40

Question

What will be the output of the following code?class MyClass:    class_variable = 10    def init(self, instance_variable):        self.instance_variable = instance_variableobj1 = MyClass(20)obj2 = MyClass(30)MyClass.class_variable = 40print(obj1.class_variable, obj2.class_variable)10 10 20 3040 4020 40

🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the code will be "40 40".

Here's the step by step explanation:

  1. A class MyClass is defined with a class variable class_variable set to 10.

  2. The class also has an initializer method __init__ that sets an instance variable instance_variable when an object of the class is created.

  3. Two objects of the class MyClass are created, obj1 and obj2, with instance_variable set to 20 and 30 respectively.

  4. The class variable class_variable is then changed to 40.

  5. When print(obj1.class_variable, obj2.class_variable) is executed, it prints the current value of class_variable for obj1 and obj2. Since class variables are shared among all instances of a class, the updated value 40 is printed for both obj1 and obj2.

This problem has been solved

Similar Questions

What will be the output of the following code?class MyClass:    def __init__(self, value=5):        self.value = valueobj1 = MyClass()obj2 = MyClass(10)print(obj1.value, obj2.value)5 1010 50 10None None

What will be the output of below Python code?class A():    def __init__(self,count=100):        self.count=countobj1=A()obj2=A(102)print(obj1.count)print(obj2.count)

What will be the output of the following Python code?class A: def __init__(self): self.__i = 1 self.j = 5  def display(self): print(self.__i, self.j)class B(A): def __init__(self): super().__init__() self.__i = 2 self.j = 7 c = B()c.display()2 71 51 72 5

what is the output of following python code? class myclass:    def __init__(self,a):        self.a = a        print(self.a)o=myclass()

What will be the output of the following Python code?class Demo: def __init__(self): self.a = 1 self.__b = 1 def get(self): return self.__bobj = Demo()obj.a=45print(obj.a)

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.