首页 > 解决方案 > 对象之间通配符匹配的简洁方法?

问题描述

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

请参考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

标签: pythonoop

解决方案


您可以使用__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

推荐阅读