__eq__
在添加属性时未被重写¶
ID: py/missing-equals
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- reliability
- correctness
Query suites:
- python-security-and-quality.qls
定义了在其超类中不存在的属性的类可能需要重写 __eq__()
方法(也应定义 __ne__()
)。
在不重写 __eq__()
的情况下添加其他属性意味着这些属性在等式测试中不会被考虑在内。
建议¶
重写 __eq__
方法。
示例¶
在以下示例中,ColorPoint
类是 Point
类的子类,并添加了一个新属性,但没有重写 __eq__
方法。
class Point(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
class ColorPoint(Point):
def __init__(self, x, y, color):
Point.__init__(self, x, y)
self._color = color
def __repr__(self):
return 'ColorPoint(%r, %r)' % (self._x, self._y, self._color)
#ColorPoint(0, 0, Red) == ColorPoint(0, 0, Green) should be False, but is True.
#Fixed version
class ColorPoint(Point):
def __init__(self, x, y, color):
Point.__init__(self, x, y)
self._color = color
def __repr__(self):
return 'ColorPoint(%r, %r)' % (self._x, self._y, self._color)
def __eq__(self, other):
if not isinstance(other, ColorPoint):
return False
return Point.__eq__(self, other) and self._color = other._color
参考¶
Peter Grogono, Philip Santas: 面向对象语言中的等式