阅 读 文 章

请问类的实例可以作为字典的key吗?

[来源:网上转载 (http://www.chinaunix.net) | 作者:网友(Rcfeng) | 时间:2007-05-27 | 浏览:人次 ]


写了一个类,实例化之后作为一个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

最新评论 共有0位网友发表了评论

发表评论

评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名:(注册)
密码:
验证码:
匿名发表

网站地图友情连接交流论坛网站投稿广告服务联系我们留言本站长统计
Some rights reserved: www.chmhome.com, 鄂ICP备07010232号 E-mail:chinakafei@live.com,QQ:552766
中国咖啡技术网(Chmhome):国外编程技术书籍,中文编程手册,经典编程文章,交流技术,技术软件下载,计算机论文,毕业论文.