Краткий способ для подстановочного совпадения среди объектов? - PullRequest
0 голосов
/ 28 июня 2018

У меня есть класс 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 голосов
/ 28 июня 2018

Вы можете использовать ваши классы __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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...