The principle of set implementation in python is not repeated, pythonset

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.