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

时间:2014-11-03 14:36:28

标签: python python-3.x compare

我有这个对象。

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

2 个答案:

答案 0 :(得分: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

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

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)

答案 1 :(得分: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)