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)
Question
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)
Solution
The output of the given Python code will be 45.
Here's the step by step explanation:
-
A class
Demois defined with an initializer method__init__. This method is automatically called when an object is created from this class. It sets the attributeato1and the attribute__bto1. The double underscore beforebmakes it a private attribute. -
A method
getis defined which returns the value of the private attribute__b. -
An object
objis created from the classDemo. This automatically calls the__init__method and setsaand__bto1. -
The attribute
aof the objectobjis set to45. -
The value of
obj.ais printed, which is45.
Similar Questions
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) The program runs properly and prints 45 The program has an error because the value of members of a class can’t be changed from outside the classThe program runs properly and prints 1 The program has an error because the value of members outside a class can only be changed as self.
class Demo: def __init__(self): self.a = 1 self.__b = 1 def get(self): return self.__bobj = Demo()obj.a=45print(obj.a)
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 below Python code?class A(): def __init__(self,count=100): self.count=countobj1=A()obj2=A(102)print(obj1.count)print(obj2.count)
what is the output of following python code? class myclass: def __init__(self,a): self.a = a print(self.a)o=myclass()
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.