ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class A:
    def __eq__(self, o):
        print("A", end=" ")
        return NotImplemented
class B:
    def __eq__(self, o):
        print("B", end=" ")
        return NotImplemented

print(A() == B(), end="; ")
print(A() != B())
  1. A. A False; A True
  2. B. A B False; A B True
  3. C. A B NotImplemented; A B NotImplemented
  4. D. A B False; True

Correct answer: B. A B False; A B True

a == b first tries A.__eq__; NotImplemented means 'ask the other side', so the reflected B.__eq__ runs. When both decline, == falls back to identity, False. For != neither class defines __ne__, and the inherited object.__ne__ calls __eq__ and inverts it unless it gets NotImplemented — so A's and then B's __eq__ are consulted again, and the final fallback for != is 'not identical': True.

More Python Programming questions

Exams that ask this topic