Classes & Objects · Question 12 · Medium
A class method reads a counter that __init__ increases on the class. What is printed after two tickets are created?
class Ticket:
count = 0
def __init__(self):
Ticket.count += 1
@classmethod
def total(cls):
return cls.count
Ticket()
Ticket()
print(Ticket.total())
- 0
- 2
- 1
- TypeError
Answer and explanation
Answer: B. 2
Explanation: Each object creation runs __init__, which adds 1 to the class attribute Ticket.count. total receives the class as cls and returns cls.count, which is 2.
Previous: The Point class defines __eq__. What do == and is give for two separately… · Next: fahrenheit is declared with @property and is accessed without brackets. What…
Practise classes & objects
Try a fresh set of classes & objects questions with an explanation after every answer, free and without signing up: Classes & Objects practice. Or sit a full placement mock test.
More classes & objects questions
- The child class Student defines its own __init__ and does not call the…
- Three classes in a chain each extend fee() using super(). What does the last…
- The Point class defines __eq__. What do == and is give for two separately…
- fahrenheit is declared with @property and is accessed without brackets. What…
- What is the key difference between a method marked @classmethod and one marked…
- B is a child of A. What do isinstance, a direct type comparison and issubclass…
- D inherits from both B and C, and B and C both inherit from A. Which who()…
- Every class in this diamond calls super().go(). What string does D().go() build?
- The Coin class defines both __str__ and __repr__. What is printed for the…
- total is a property with only a getter. What happens when the code tries to…
More python practice
Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge