CodeQL 文档

不一致的相等和不等

ID: py/inconsistent-equality
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - reliability
   - correctness
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 存储库中的查询

为了符合对象模型,类应该定义没有相等方法,或者同时定义相等和不等方法。如果只定义了 __eq____ne__ 中的一个,那么将使用超类的方法。这不太可能导致预期的行为。

建议

当您为类定义相等或不等方法时,请记住同时实现 __eq__ 方法和 __ne__ 方法。

示例

在以下示例中,PointOriginal 类定义了相等方法,但没有定义不等方法。如果此类被测试为不相等,则会引发类型错误。PointUpdated 类更好,因为它同时定义了相等和不等方法。为了完全符合对象模型,此类还应该定义一个哈希方法(由单独的规则识别)。

class PointOriginal(object):

    def __init__(self, x, y):
        self._x, x
        self._y = y

    def __repr__(self):
        return 'Point(%r, %r)' % (self._x, self._y)

    def __eq__(self, other):  # Incorrect: equality is defined but inequality is not
        if not isinstance(other, Point):
            return False
        return self._x == other._x and self._y == other._y


class PointUpdated(object):

    def __init__(self, x, y):
        self._x, x
        self._y = y

    def __repr__(self):
        return 'Point(%r, %r)' % (self._x, self._y)

    def __eq__(self, other):
        if not isinstance(other, Point):
            return False
        return self._x == other._x and self._y == other._y

    def __ne__(self, other):  # Improved: equality and inequality method defined (hash method still missing)
        return not self == other

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私