对象之间通配符匹配的简便方法?

时间:2018-06-28 07:17:14

标签: python oop

我有一个Match类,需要实现一个wildcard match方法。此方法将使用同一类的另一个对象检查该类的所有属性。如果两者相同或两者均为*,则为匹配项。这个逻辑对于一个类中的所有属性都是正确的。

请参考以下wildcard_match方法的实现。

问题是,如果我向类中添加了更多属性,或者属性的数量很大,则需要手动继续添加到方法中。因此,我需要一种简洁,干燥的方法来实现该方法。

感谢您的帮助。

class Match:
    def __init__(self):
        self.src = "h%s" % random.randint(1, SRC)
        self.dst = "h%s" % random.randint(1, DST)
        self.proto = random.choice(L4_PROTO)
        self.src_port = str(random.randint(2000, 5000))
        self.dst_port =  random.choice(L4_PORTS)

    def __members(self):
        return (self.src, self.dst, self.proto, self.src_port, self.dst_port)

    def __hash__(self):
        return hash(self.__members())

    def __eq__(self, other):
        """ Exact match check """
        if isinstance(other, self.__class__):
            return self.__members() == other.__members()
        else:
            return False

    def wildcard_match(self, other):
        """ Check whether the two matches are a wildcard match """
        if isinstance(other, self.__class__):
            if self.src != "*" and other.src != "*" and self.src != other.src:
                return False
            if self.dst != "*" and other.dst != "*" and self.dst != other.dst:
                return False
            if self.proto != "*" and other.proto != "*" and self.proto != other.proto:
                return False
            if self.src_port != "*" and other.src_port != "*" and self.src_port != other.src_port:
                return False
            if self.dst_port != "*" and other.dst_port != "*" and self.dst_port != other.dst_port:
                return False
            return True
        else:
            return False

1 个答案:

答案 0 :(得分:1)

您可以使用包含您定义的所有属性的类__dict__

def wildcard_match(self, other):
    """ Check whether the two matches are a wildcard match """
    if isinstance(other, self.__class__):
        for attr_name in self.__dict__:
            self_attr = self.__getattr__(attr_name)
            other_attr = other.__getattr__(attr_name)
            if self_attr != "*" and other_attr != "*" and self_attr != other_attr:
                return False
        return True
    else:
        return False
相关问题