2012-10-07 67 views
0

是否有可能實現一個類的方法,以便它的對象與set()函數一起使用?所以Set(objarray)會返回唯一的對象。當然,創建我自己的套裝是一種選擇,但如果它已經在那裏,我不想重新發明輪子。運算符重載Python

編輯:我想我讓你的傢伙與我的英語混淆。這就是我在班上所擁有的 - 我有一個Person類,其人名和地址作爲其成員。這是我想要做的 -

persons = [] 
for i in range (50): 
    name = raw_input("Enter Name") 
    address = raw_input("Address") 
    persons.append(Person(name,address)) 
unique = Set(persons) #would only return one person from an address. 
         #The rest from the same address will be removed 

我希望明確的困惑。

+0

閱讀您的標題和內容再次。如何在地球上它們是相關的? –

+0

嗯,我認爲它與運算符重載有關cuz Set方法適用於字典,我希望我的類可以像字典一樣工作。 – Andrew

+0

他可能想重載平等測試。 – cdhowie

回答

2

是的。首先,如果你的類既沒有實現__hash__也沒有實現__eq__,那麼它們已經是可散列的(id被用作散列值並且比較由is完成)。

或者,如果您實現__hash____eq__,那麼你的類實例可以安全地在一組或作爲字典鍵使用:

>>> class Foo: 
...  def __init__(self, val): self.val = val 
...  def __hash__(self): return hash(self.val) 
...  def __eq__(self, other): return self.val == other.val 
...  def __repr__(self): return 'Foo(%r)' % self.val 
... 
>>> print set([Foo(3), Foo("bar")]) 
set([Foo(3), Foo('bar')]) 

如果你希望能夠直接調用set上的情況下,你的類,過載__iter__,使類的實例似乎是迭代:

>>> class CharSeq: 
...  def __init__(self, first, last): 
...   self.first = ord(first) 
...   self.last = ord(last) 
...  def __iter__(self): 
...   return (chr(i) for i in xrange(self.first, self.last+1)) 
... 
>>> set(CharSeq('a', 'c')) 
set(['a', 'c', 'b']) 
+0

我想他想做'set(Foo(3))' –

+0

他的評論表明,但原來的問題表明否則......呃,我只是將兩種解釋都放在答案中。謝謝。 – nneonneo

+1

鏈接官方文檔總是很好 - 因爲有些角落案例可能會讓你感興趣。 http://docs.python.org/reference/datamodel.html#object.__hash__ – jsbueno