What do these lines print?class Base(): """ My base class """ __nb_instances = 0 def __init__(self): Base.__nb_instances += 1 self.id = Base.__nb_instancesb = Base()print(b.id)
Question
What do these lines print?class Base(): """ My base class """ __nb_instances = 0 def init(self): Base.__nb_instances += 1 self.id = Base.__nb_instancesb = Base()print(b.id)
Solution
The code defines a class Base with a private class variable __nb_instances initialized to 0. The __init__ method increments __nb_instances by 1 each time an instance of Base is created and assigns the current value of __nb_instances to the instance variable id.
When b = Base() is executed, an instance of Base is created. This triggers the __init__ method, which increments __nb_instances to 1 and assigns this value to b.id.
Therefore, print(b.id) will output 1.
Similar Questions
What do these lines print?class Base(): """ My base class """ __nb_instances = 0 def __init__(self): Base.__nb_instances += 1 self.id = Base.__nb_instancesclass User(Base): """ My User class """ def __init__(self): super().__init__() self.id += 99u = User()print(u.id)991100I don't know
class Base(): """ My base class """ __nb_instances = 0 def __init__(self): Base.__nb_instances += 1 self.id = Base.__nb_instancesclass User(Base): """ My User class """ def __init__(self): super().__init__() self.id = 89u = User()print(u.id)
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: 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)
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()
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.