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__()u = User()print(u.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_instancesclass User(Base): """ My User class """ def init(self): super().init()u = User()print(u.id)
Solution
The code defines two classes, Base and User. Base has a private class variable __nb_instances which is incremented each time an instance of Base (or any of its subclasses) is created. The id of each instance is set to the current number of instances.
User is a subclass of Base and it doesn't override the __init__ method, so it uses the one from Base.
When u = User() is executed, an instance of User is created. This calls Base's __init__ method, which increments __nb_instances and sets u's id to the new value of __nb_instances.
Finally, print(u.id) prints the id of u, which is 1. So, the output of this code is 1.
Similar Questions
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 do these lines print?class Base(): """ My base class """ __nb_instances = 0 def __init__(self): Base.__nb_instances += 1 self.id = Base.__nb_instancesfor i in range(3): b = Base()print(b.id)
what is the output of following python code? class myclass: def __init__(self,a): self.a = a print(self.a)o=myclass("Welcome")
What do these lines print?>>> class User:>>> id = 89>>> name = "no name">>> __password = None>>> >>> def __init__(self, new_name=None):>>> self.is_new = True>>> if new_name is not None:>>> self.name = new_name>>> >>> u = User()>>> u.name
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)
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.