What do these lines print?class User: id = 1u = User()User.id = 98print(u.id)89None981I don't know
Question
What do these lines print?class User: id = 1u = User()User.id = 98print(u.id)89None981I don't know
Solution
These lines print "98".
Here's the step by step explanation:
- A class named
Useris defined with a class attributeidset to1. - An instance
uof the classUseris created. - The class attribute
idof theUserclass is changed to98. - When
print(u.id)is called, it prints the current value ofidin the context of the instanceu. Sinceudoesn't have an instance attributeid, it refers to the class attributeidwhich is98. Hence,98is printed.
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): self.id = 89u = User()print(u.id)
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 will be the output of the following Python code?class Student: def __init__(self,id): self.id = id print(self.id, end=" ") std=Student(5)std.id=7print(std.id, end=" ")
What do these lines print?>>> a = { 'id': 89, 'name': "John" }>>> a.get('id')id‘id’a[‘id’]John89
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.