Knowee
Questions
Features
Study Tools

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

Question

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

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

Solution

The output of the Python code will be 1 7.

Here's the step-by-step explanation:

  1. Class A is defined with a private variable __i and a public variable j. The display method prints the values of these variables.

  2. Class B is a subclass of A and is defined with its own private variable __i and public variable j.

  3. When an object c of class B is created, the __init__ method of class B is called. This method first calls the __init__ method of the superclass A using super().__init__(), which initializes __i to 1 and j to 5.

  4. Then, the __init__ method of class B changes the values of __i and j to 2 and 7 respectively. However, __i is a private variable, so the change only applies within the scope of class B. The __i in class A remains 1.

  5. Finally, when c.display() is called, the display method of the superclass A is executed because class B does not override this method. This method prints the values of __i and j as defined in class A, which are 1 and 7 respectively. The value of j is 7 because it's a public variable and was updated in the __init__ method of class B.

This problem has been solved

Similar Questions

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

What is the output of the following code?        python    class A:        def display(self):            print("Class A")    class B(A):        def display(self):            print("Class B")    class C(A):        def display(self):            print("Class C")    obj = B()    obj.display()    obj = C()    obj.display()

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 code?class MyClass:    def __init__(self, value=5):        self.value = valueobj1 = MyClass()obj2 = MyClass(10)print(obj1.value, obj2.value)

What will be the output of the following Python code?class fruits: def __init__(self): self.price = 100 self.__bags = 5 def display(self): print(self.__bags)obj=fruits()obj.display()

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.