Interview Q&A / Python

INTERVIEW Q&A · 81 QUESTIONS

Python interview questions

Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.

  1. Why must you define __hash__ when you define __eq__ for objects used in sets or as dict keys?

    Objects that compare equal must have the same hash, or sets and dicts will treat them as different. Defining __eq__ without __hash__ sets __hash__ to None, so the class becomes unhashable. Base the hash on the same fields that __eq__ compares.

    AdvancedQuick answer1 min read