class Myclass: x=0 def incre(self): self.x+=1 def disp(self): print(self.x)ob1=Myclass()ob1.incre()ob1.disp()ob2=Myclass()ob2.incre()ob2.disp()0 01 21101
Question
class Myclass: x=0 def incre(self): self.x+=1 def disp(self): print(self.x)ob1=Myclass()ob1.incre()ob1.disp()ob2=Myclass()ob2.incre()ob2.disp()0 01 21101
Solution
The code you've posted seems to be written in Python and it's defining a class Myclass with a class variable x, and two methods incre and disp.
Here's a step-by-step explanation:
-
class Myclass:This line is defining a new class namedMyclass. -
x=0This line is defining a class variablexand initializing it to 0. -
def incre(self):This line is defining a methodincrewhich will increment the value ofxby 1. -
self.x+=1This line is incrementing the value ofxby 1. -
def disp(self):This line is defining a methoddispwhich will print the current value ofx. -
print(self.x)This line is printing the current value ofx. -
ob1=Myclass()This line is creating an instance ofMyclassnamedob1. -
ob1.incre()This line is calling theincremethod onob1, which will incrementxby 1. -
ob1.disp()This line is calling thedispmethod onob1, which will print the current value ofx. -
ob2=Myclass()This line is creating another instance ofMyclassnamedob2. -
ob2.incre()This line is calling theincremethod onob2, which will incrementxby 1. -
ob2.disp()This line is calling thedispmethod onob2, which will print the current value ofx.
The output of this code will be:
1
1
This is because each instance of Myclass has its own x variable. When incre is called on ob1, it increments ob1's x from 0 to 1. Similarly, when incre is called on ob2, it increments ob2's x from 0 to 1.
Similar Questions
what will be the output of the following code?class Myclass: x=0 def incre(self): self.x+=1 def disp(self): print(self.x)ob1=Myclass()ob1.incre()ob1.disp()ob2=Myclass()ob2.incre()ob2.disp()
class Demo: def __init__(self): self.a = 1 self.__b = 1 def get(self): return self.__bobj = Demo()obj.a=45print(obj.a)
class One: def __str__(self): return '1'class Two(One): def __init__(self): super().__init__()class Three(Two): def __init__(self): super().__init__()def main(): object1 = Two() object2 = One() object3 = Three() print(object1, object2, object3)
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 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
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.