python - 对象之间通配符匹配的简洁方法?
问题描述
我有一个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
解决方案
您可以使用__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
推荐阅读
- python - 从两个基础镜像(centos 和 python)构建一个新的 docker 镜像
- c# - 将内容和编译文件从 nuget 复制到 .net 核心项目中
- shell - VB6 - 当我单击命令按钮时如何执行存储在字符串变量中的文件
- node.js - nodejs中函数外的json变量的范围是什么?
- reactjs - TS2339 Typescript 错误,但不确定为什么...类型上不存在属性
- java - Java swing.How to override component methods in intellij idea GUI desinger
- git - 让 Git Bisect 进行强制签出或以其他方式覆盖本地更改
- excel - 在 VBA 中的图形上绘制一个点
- python - 如何将 django 模型表单放入现成的模板中
- python - 在网络浏览器中定期打开的某些 url 上没有得到 urllib 响应