Python — перегрузка
операторов, магические методы — казалось
бы, что тут сложного? Сложного ничего,
но есть тонкости.
так здорово
изложено, что я не смог удержаться и
утянул дайджест к себе:
class Point(object):
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@property
def y(self):
return self._y
def __hash__(self):
# Определять только __hash__ без __eq__/__ne__ неправильно: в случае коллизии задействуются операторы сравнения. Если они не определены -- можно получить некорректный результат
return hash((self._x, self._y))
def __eq__(self, other):
# Чтобы сказать, что операция сравнения не дает результата -- нужно вернуть константу NotImplemented (не путать с исключением NotImplementedError):
if not isinstance(other, Point):
return NotImplemented
return self._x == other._x and self._y == other._y
def __ne__(self, other):
return not (self == other)
def __sub__(self, other):
if not isinstance(other, Point):
return NotImplemented
return Point(self._x - other._x, self._y - other._y)
def __rsub__(self, other):
if not isinstance(other, Point):
return NotImplemented
return other - self
def __add__(self, other):
if isinstance(other, Point):
return Point(self._x + other._x, self._y + other._y)
elif isinstance(other, QPoint):
return Point(self._x + other.x(), self._y + other.y())
return NotImplemented
def __radd__(self, other):
if isinstance(other, Point):
return Point(self._x + other._x, self._y + other._y)
elif isinstance(other, QPoint):
return Point(other.x() - self._x, other.y() - self._y)
return NotImplemented
|
Почему так а
не иначе, читайте у автора:
http://asvetlov.blogspot.ru/2014/09/magic-methods.html
original post http://vasnake.blogspot.com/2014/10/magic-methods.html

Комментариев нет:
Отправить комментарий