写了一个类,实例化之后作为一个dic的key,但是出现 TypeError: unhashable instance。
我记得看过Learning Python中说过,甚至类的实例也可以作为字典的键,请问有什么特殊要求吗?
wolfg 回复于:2005-09-23 10:49:02
The object must be immutable
Rcfeng 回复于:2005-09-23 10:49:13
"And class instance objects (discussed in Part VI) can be used as keys too, as long as they have the proper protocol methods;roughly, they need to tell Python that their values won't change, or else they would be useless as fixed keys."
上面是Learning Python中说的,请问怎么告诉python我这个类的实例是不变的呢?
limodou 回复于:2005-09-23 10:56:14
我试了一下没有问题。你的代码是什么,可能是别的错误。
>;>;>; class A:
... pass
>;>;>; a=A()
>;>;>; b={a:1}
>;>;>; b[a]
1
Rcfeng 回复于:2005-09-23 11:05:15
你试着定义一个__init__,然后定义两个成员变量再试试呢?
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 printip(self):
# print "Low: %d; Up: %d" % (self.low_ip,self.up_ip)
def __cmp__(self,ip):
if( ip>;=low_ip and ip<=up_ip ):
return 0
elif( ip<low_ip ):
return -1
else: return 1
ip_map[ip(ip1,ip2)] = text
这样是不行的~
wolfg 回复于:2005-09-23 11:21:41
引用:原帖由 "Rcfeng"]p2)] 这样是不行的~
发表:
不使用内置的__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)
| 论坛热门帖子: | [lch203] 写得蛮好的linux学习笔记(10-21) [黑马制造] 学习java的30个目标(10-19) [笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19) [udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18) [沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18) |
| TAG标签: | 作为 可以 实例 请问 ip hash self 回复 ipstr oneinf |
注册
个人空间
