我有一本下列形式的词典:
{ <Category('Simulate', 'False', 'False', 'False', 'INTERMEDIATE')>: {'link': u'/story/4/tvb-adapters-simulator-simulatorAdapter/SimulatorAdapter', 'name': u'Simulate'},
<Category('View Results', 'True', 'False', 'True', 'INTERMEDIATE')>: {'link': '/story/step/3', 'name': u'View Results'},
<Category('Analyze', 'True', 'False', 'False', 'FINAL')>: {'link': '/story/step/2', 'name': u'Analyze'}}
Category是表示数据库中实例的类。现在我有以下实例:
<Category('Analyze', 'True', 'False', 'False', 'FINAL')>
这不是同一个例子。我是说,我从数据库中获取所有值并创建字典。过了一会儿,我得到一个id并从数据库中检索实例。现在它们不是同一个物体了。我现在要检查字典里有没有,但是:
instance in disctionary
将返回false。现在,我可以用一种难看的方式遍历字典,检查所有的值是否都匹配,但是Python有更聪明的方法来做到这一点吗?我的意思是类似于Java中的Comparable?
首先:使用
True
和False
(布尔属性),而不是'True'
和'False'
(字符串属性)。一般来说,您可以在Python中使所有内容都具有可比性。你只需要为你的类定义特定的方法(比如
__eq__
,__lt__
,等等)。所以,假设我想比较类A的实例,并且比较应该是
s
成员的不区分大小写的字符串比较:而不是使用
Category
(例如Category('Analyze', 'True', 'False', 'False', 'FINAL')
)的实例作为字典中的键, 听起来您应该使用关联的元组(例如('Analyze', 'True', 'False', 'False', 'FINAL')
)。如果您确实想使用} 和
Category
的实例作为字典中的键,则需要同时定义^{__eq__
方法。 例如:a
和b
是不同的实例,因此它们具有不同的id
s,但它们的哈希值相同:这表明
b
是mydict
中可接受的键:另外,不用担心
__cmp__
。In Python 3:显然,您可以将类别实例放入dict中,因此必须已经覆盖了
__hash__
。现在你只需要__eq__
:真正应该做的是扔掉整个类并使用
collections.namedtuple
来代替:相关问题 更多 >
编程相关推荐