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
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() self.id += 99u = User()print(u.id)991100I don't know
Solution
The code prints "100". Here's the step-by-step explanation:
-
The
Baseclass is defined with a private class variable__nb_instancesinitialized to 0. This variable is used to keep track of the number of instances of the class. -
The
__init__method of theBaseclass increments__nb_instancesby 1 each time an instance is created and assigns the value of__nb_instancesto the instance variableself.id. -
The
Userclass is a subclass ofBase. Its__init__method first calls the__init__method of theBaseclass usingsuper().__init__(), which increments__nb_instancesand assigns the value toself.id. -
Then, the
Userclass's__init__method incrementsself.idby 99. -
When
u = User()is executed, an instance ofUseris created. This is the first instance ofBase, so__nb_instancesis incremented to 1 andself.idis set to 1. Thenself.idis incremented by 99, sou.idis 100. -
Finally,
print(u.id)prints "100".
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_instancesb = Base()print(b.id)
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("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.id89idUser.idNothing
What do these lines print?class User: id = 1u = User()User.id = 98print(u.id)
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.