Using a custom class instance as a dictionary key in Python

Source: Internet
Author: User

The key value of the Dict type in Python is immutable, and generally we use the int or str type as the key for the dictionary, but in some scenarios it can be a problem.

If we have a rule that handles HTTP request, it is defined as follows, which consists of a request path and its supported request methods array:

class Rule (object):     def __init__ (self, Path, methods):         assert (isinstance (path, str))         assert (Isinstance (Methods, list))         = path        for in methods]

Now we want to associate a corresponding handler object for each rule (not every rule instance), using a dict to save the correspondence.

R1 = Rule ("/index", ["GET"= Rule ("/ Index", ["GET"= {r1:handler}Print  D[R2]#  two different objects, print none

Although R1 and R2 are two different object instances, they are consistent in business logic, so if we want two logically consistent objects to be considered the same key, there are some ways to achieve this effect.

Add two methods __hash__ and __eq__ to rule, meaning you can view the official Python documentation.

classRule (object):def __init__(self, Path, methods):assert(isinstance (path, str))assert(Isinstance (Methods, list)) Self.path=Path Self.methods= [Method.upper () forMethodinchmethods]def __hash__(self):returnHash ((Self.path, str (self.methods)))def __eq__(self, Other):return(Self.path, self.methods) = = (Other.path, other.methods)

Then execute the above test code, found that can be successfully taken to the handler:

R1 = Rule ("/index", ["GET"= Rule ("/ Index", ["GET"= {r1:handler}Print  = = Handler#  print out True

Using a custom class instance as a dictionary key in Python

Related Article

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.