- 论坛徽章:
- 0
|
请问类的实例可以作为字典的key吗?
原帖由 "Rcfeng"]p2)] 这样是不行的~[/quote 发表:
不使用内置的__cmp__方法就行了
- class ip:
- "A Ip class for finding user's area"
- def __init__(self, low_ip, up_ip):
- self.low_ip = low_ip
- self.up_ip = up_ip
- def __str__(self):
- return "Low: %d; Up: %d" % (self.low_ip,self.up_ip)
- def cmpare(self,ip):
- if( ip>;=low_ip and ip<=up_ip ):
- return 0
- elif( ip<low_ip ):
- return -1
- else: return 1
复制代码
可能是有了__cmp__就认为是可变的了
Python文档里找到这么一句
[quote]Instances of a class normally compare as non-equal unless the class defines the __cmp__() method.
__cmp__( self, other)
Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self >; other. If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity (``address''). See also the description of __hash__() for some important notes on creating objects which support custom comparison operations and are usable as dictionary keys. (Note: the restriction that exceptions are not propagated by __cmp__() has been removed since Python 1.5.)
看了__hash__的介绍,终于明白了
__hash__( self)
Called for the key object for dictionary operations, and by the built-in function hash(). Should return a 32-bit integer usable as a hash value for dictionary operations. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object that also play a part in comparison of objects. If a class does not define a __cmp__() method it should not define a __hash__() operation either; if it defines __cmp__() or __eq__() but not __hash__(), its instances will not be usable as dictionary keys. If a class defines mutable objects and implements a __cmp__() or __eq__() method, it should not implement __hash__(), since the dictionary implementation requires that a key's hash value is immutable (if the object's hash value changes, it will be in the wrong hash bucket).
If a class does not define a __cmp__() method it should not define a __hash__() operation either; if it defines __cmp__() or __eq__() but not __hash__(), its instances will not be usable as dictionary keys. |
|