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): 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): 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. -
In the
__init__method of theUserclass, theself.idattribute is set to 89. -
When
print(u.id)is called, it prints theidattribute of theuobject, which is 89.
Note: The __nb_instances attribute and its increment in the Base class __init__ method are not affecting the output of this code because the User class does not call super().__init__() to invoke the initialization of the Base class.
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 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.