English 中文(简体)
贾瓦的“ Python”等同物是什么?
原标题:What is the Python equivalent of Comparables in Java?
  • 时间:2011-08-05 09:54:06
  •  标签:
  • python

我有以下表格的字典:

{ <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( Analyze ,  True ,  False ,  False ,  FINAL )>

现在情况并非如此。 因此,我从数据库中获取所有价值,并创建词典。 之后,我得到一个id,并从数据库中取回了这个例子。 现在,它们不是同一个目标。 现在我必须检查一下这是否在独裁者,但:

instance in disctionary

否则就不实。 现在,如果所有价值观都相符,我可以直截了当,听从独裁检查,但沙尔这样做的路程会越紧? 我指的是 Java可比的东西?

最佳回答

首先:使用<代码>True和(False(boolean property)而不是 页: 1 False (string nature).

Generally, you can make everything comparable in Python. You just have to define specific methods (like __eq__, __lt__, etc.) for your class.

因此,我要说的是,我要比较A类的情况,而比较应当只是对<条码>/代码>成员的个案敏感地比较:

class A(object):
    def __init__(self, s=  ):
        self.s = s

    def __eq__(self, other):
        return self.s.lower() == other.s.lower()

a = A( aaaa )
b = A( AAAA )
print a == b # prints True
b = A( bbbb )
print a == b # prints False
问题回答

Instead of using instances of Category (e.g. Category( Analyze , True , False , False , FINAL )) as the keys in your dictionary, it sounds like you should be using the associated tuple (e.g. ( Analyze , True , False , False , FINAL )).

If you really do want to use instance of Category as the keys in the dictionary, you ll need to define both the __hash__ and __eq__ methods. For example:

class Category(object):
    def __init__(self,*args):
        self.args=args
    def __hash__(self):
        # Note that this assumes that Category s hash value is immutable
        # i.e. self.args does not change.
        return hash(self.args)
    def __eq__(self,other):
        return self.args == other.args

a=Category( Analyze ,  True ,  False ,  False ,  FINAL )
b=Category( Analyze ,  True ,  False ,  False ,  FINAL )

mydict={a:1}

<代码>a和b是不同的事例,因此它们有不同的<代码>ids,但它们的散射数值相同:

assert id(a) != id(b)
assert hash(a)==hash(b)

b是mydict可接受的关键:

print(mydict[a])
# 1
print(mydict[b])
# 1

PS。 http://docs.python.org/release/3.0.1/whatsnew/3.0.html#ordering-comparisons”rel=“nofollow”

The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed.

由于你显然能够把你的类别事例列入一个字典,你必须拥有已经过时的“条码”_hash_。 现在需要的是<代码>_eq__:

class Category(object):
    # you must have overwritten `__hash__` like this already
    def __hash__(self):
        return hash((self.attr1, self.attr2, ... ))

    # now you just need tis
    def __eq__(self, other):
        return isinstance(other, Category) and 
               (self.attr1, self.attr2, ... ) == (other.attr1, other.attr2, ... )

你们应该做的是,放弃整个类别,使用<条码>,代之以:

Category = collections.namedtuple( Category ,  attr1 attr2 attr3 )

可能有一些捷径,如使用胶卷,但回答贵方问题的一般答案是:执行__eq__(<>>>/code>,供您的班级使用,以便(......)使用,而不是测试身份。

<in和其他工作比较操作者,必须执行_hash__cmp__。 (或_eq_等“浓缩”比较方法。) 见。 Zhu reference





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...