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
Solution
The output of the Python code will be 1 7.
Here's the step-by-step explanation:
-
Class
Ais defined with a private variable__iand a public variablej. Thedisplaymethod prints the values of these variables. -
Class
Bis a subclass ofAand is defined with its own private variable__iand public variablej. -
When an object
cof classBis created, the__init__method of classBis called. This method first calls the__init__method of the superclassAusingsuper().__init__(), which initializes__ito1andjto5. -
Then, the
__init__method of classBchanges the values of__iandjto2and7respectively. However,__iis a private variable, so the change only applies within the scope of classB. The__iin classAremains1. -
Finally, when
c.display()is called, thedisplaymethod of the superclassAis executed because classBdoes not override this method. This method prints the values of__iandjas defined in classA, which are1and7respectively. The value ofjis7because it's a public variable and was updated in the__init__method of classB.
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()
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.