python - 在 Python 中实现比较类的 OOP 方法

标签 python matching readability

我正在尝试使用 Python 实现一组类型,包括用于模糊匹配的“无关”类型。我是这样实现的:

class Matchable(object):        
    def __init__(self, match_type = 'DEFAULT'):
        self.match_type = match_type

    def __eq__(self, other):
        return (self.match_type == 'DONTCARE' or other.match_type == 'DONTCARE' \
or self.match_type == other.match_type)

来自 OO 背景,这个解决方案似乎不够优雅;使用 Matchable 类会导致代码难看。我宁愿消除 match_type,而是让每个类型成为它自己的类,继承自父类(super class),然后使用类型检查来进行比较。然而,类型检查似乎通常不受欢迎:

http://www.canonical.org/~kragen/isinstance/

是否有更好(更 pythonic)的方式来实现此功能?

注意:我知道关于 Python“枚举”的大量问题和答案,可能其中一个答案是合适的。覆盖 __ eq __ 函数的要求使事情变得复杂,而且我还没有看到针对这种情况使用建议的枚举实现的方法。

我能想到的最好的 OO 方法是:

class Match(object):
    def __eq__(self, other):
        return isinstance(self, DontCare) or isinstance(other, DontCare) or type(self) == type(other)

class DontCare(Match):
    pass

class A(Match):
    pass

class B(Match):
    pass

d = DontCare()
a = A()
b = B()


print d == a
True
print a == d
True
print d == b
True
print a == b
False
print d == 1
True
print a == 1
False

最佳答案

你链接的文章说 isinstance 并不总是邪恶的,我认为你的情况是合适的。文章中的主要提示是使用 isinstance 检查对象是否支持特定接口(interface)会减少使用隐含接口(interface)的机会,这是一个公平的观点。但是,在您的情况下,您本质上将使用 Dontcare 类来提供关于在比较中应如何处理对象的注释,而 isinstance 将检查此类注释,这应该是完美的。很好。

关于python - 在 Python 中实现比较类的 OOP 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15775467/

相关文章:

r - 将已排序数据框中的最近值绘制到未排序数据框中

python - 处理大型 if/else 的最佳方法

python循环求和函数

python - 尝试让 pandas python 代码更短

python - 如何迭代类属性而不是函数并在 python 中返回属性值?

正则表达式匹配排序

python - 我无法完全理解这行代码

java - 降低大型 switch 语句的复杂性

Python如何包含另一个文件中的函数