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 = 89u = 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() self.id = 89u = User()print(u.id)
Solution
The code will print "89".
Here's the step-by-step explanation:
-
The
Userclass is a subclass of theBaseclass. -
When an instance of the
Userclass is created withu = User(), the__init__method of theUserclass is called. -
Inside the
Userclass's__init__method,super().__init__()is called. This calls the__init__method of the superclass, which isBase. -
Inside the
Baseclass's__init__method,Base.__nb_instancesis incremented by 1 andself.idis set toBase.__nb_instances. However, thisself.idis theidof theBaseclass, not theUserclass. -
After the
super().__init__()call,self.idis set to 89. Thisself.idis theidof theUserclass. -
When
print(u.id)is called, it prints theidof theUserinstanceu, which is 89.
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__()u = 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 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.