2014-11-03 66 views
0

我有这个对象。如何比较两个对象,但只是不是没有属性

class Token(object): 
    def __init__(self, word = None, lemma = None, pos = None, head = None, synt = None): 
     self.word = word.lower() 
     self.lemma = lemma 
     self.pos = pos 
     self.head = head 
     self.synt =synt 

并在某些时候我填写一些属性。现在我需要比较2个对象,但只是他们不是无的属性。有没有一些简单的方法来做到这一点?

我尝试嵌套的if语句,但它是混淆,并不能正常工作。

事情是这样的:

def compareTokens(t1,t2): 
    if t1.word is not None and t1.word == t2.word: 
     if t1.lemma is not None and t1.lemma == t2.lemma: 
      if t1.pos is not None and t1.pos == t2.pos: 
       return True 
    else: 
     return False 

回答

3

如果颠倒测试,你可以遍历 所需的属性,尽快返回false。只有在达到for循环的结尾时才返回True。

import operator 

def compare_tokens(t1, t2): 
    if any(x is None for x in operator.attrgetter('word', 'lemma', 'pos')(t1) 
    for getter in [operator.attrgetter(x) for x in 'word', 'lemma', 'pos']: 
     if getter(t1) is None or getter(t1) != getattr(t2): 
      return False 
    return True 

另一种选择是在看t2之前测试中t1所有值:

def compare_tokens(t1, t2): 
    getter = operator.attrgetter('word', 'lemma', 'pos') 
    t1_values = getter(t1) 
    if any(x is None for x in t1_values): 
     return False 
    return t1_values == getter(t2) 
+0

我一直在寻找这样的事情。 TY! – Tzomas 2014-11-04 08:31:59

0
class Token(object): 
    def __init__(self, word=None, lemma=None, pos=None, head=None, synt=None): 
     self.head = head 
     self.lemma = lemma 
     self.pos = pos 
     self.synt = synt 
     # Whatch out with this. Before if word=None then word.lower() == Boom! 
     self.word = word.lower() if word is not None else None 

    def _cmp(self): 
     """Attributes that your class use for comparison.""" 
     return ['word', 'lemma', 'pos'] 

def compare_tokens(t1, t2): 
    assert(hasattr(t1, '_cmp')) 
    assert(hasattr(t2, '_cmp')) 
    unique = list(set(t1._cmp()) | set(t2._cmp())) 
    for attr in unique: 
     if (not hasattr(t1, attr) or not hasattr(t2, attr)): 
      return False 
     if (getattr(t1, attr) is None or 
       getattr(t1, attr) != getattr(t2, attr)): 
      return False 
    return True 

t1 = Token('word', 'lemma', 1, 'head1', 'synt1') 
t2 = Token('word', 'lemma', 1, 'head2', 'synt2') 
print compare_tokens(t1, t2)