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