The principle of set implementation in python is not repeated, pythonset
Recently I encountered a problem when trying to write the Course Selection System:
1. There are two classes: School and Teacher;
2. The School instance contains multiple Teacher instances, but cannot be repeated.
I want to use set () for storage in School, but I cannot deduplicate it when I add a Teacher instance. I guess the result is that set will automatically call the _ eq _ method to compare whether the object is repeated, therefore, this method is rewritten:
Def _ eq _ (self, other): return self. name = other. name
The error TypeError: unhashable type is returned as follows:
After studying for a long time, we found that the reason why Teacher cannot hash is that the _ hash _ method is missing in the class, and the interpreter does not know how to hash the object. The problem is solved after the following code is added:
Def _ hash _ (self): return hash (self. name)
Conclusion:
If you want to deduplicate an object with set, you need to override the _ eq _ and _ hash _ methods.