ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
class P:
    def __init__(self, x):
        self.x = x
    def __eq__(self, o):
        return self.x == o.x
try:
    print(len({P(1)}))
except TypeError as e:
    print(type(e).__name__)
  1. A. AttributeError
  2. B. TypeError
  3. C. 1
  4. D. 0

Correct answer: B. TypeError

Defining __eq__ without __hash__ sets __hash__ to None, so instances are unhashable. Putting one in a set raises TypeError, which the except block prints.

More Python Programming questions

Exams that ask this topic