What will be the output of the following code?class MyClass: def __init__(self, value): self.value = valueobj = MyClass(10)print(obj.value)
Question
What will be the output of the following code?class MyClass: def init(self, value): self.value = valueobj = MyClass(10)print(obj.value)
Solution
The output of the code will be 10.
Here's the step by step explanation:
-
A class named
MyClassis defined with an__init__method. The__init__method is a special method in Python, which is automatically called when an object of the class is created. It is used to initialize the attributes of the class. -
In the
__init__method,selfrepresents the instance of the class andvalueis a parameter that will be passed when an object of this class is created. -
An object
objofMyClassis created with the value10. This value is passed to the__init__method, soself.valuebecomes10. -
print(obj.value)prints the value of thevalueattribute of theobjobject, which is10.
Similar Questions
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
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 fruits: def __init__(self): self.price = 100 self.__bags = 5 def display(self): print(self.__bags)obj=fruits()obj.display()
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 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)
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.