What will be the output of below Python code?class A: def __init__(self,num): num=3 self.num=num def change(self): self.num=7a=A(5)print(a.num)a.change()print(a.num)
Question
What will be the output of below Python code?class A: def init(self,num): num=3 self.num=num def change(self): self.num=7a=A(5)print(a.num)a.change()print(a.num)
Solution
The output of the given Python code will be:
5 7
Here's the step by step explanation:
-
An object 'a' of class 'A' is created with the initial value of 'num' as 5.
-
When the object is created, the init method is called. Inside this method, the value of 'num' is changed to 3. However, this change is local to the init method and does not affect the 'num' attribute of the object 'a'. So, 'a.num' remains 5.
-
'print(a.num)' is called, which prints the current value of 'a.num', which is 5.
-
The 'change' method of object 'a' is called. Inside this method, 'a.num' is changed to 7.
-
'print(a.num)' is called again, which now prints the updated value of 'a.num', which is 7.
Similar Questions
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 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 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)
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.