在NumPy中,`+`如何翻译为`__add__`?

dxxyhpgq  于 2024-01-08  发布在  其他
关注(0)|答案(3)|浏览(199)

我有兴趣从代码库中+的实现中了解NumPy中的广播如何工作。
当在NumPy中写入a + b时,程序如何理解+的含义?
虽然我在/numpy/numpy/array_API/_array_object.py中找到了__add__方法,但我不清楚+如何触发此方法:

  1. def __add__(self: Array, other: Union[int, float, Array], /) -> Array:
  2. """
  3. Performs the operation __add__.
  4. """
  5. other = self._check_allowed_dtypes(other, "numeric", "__add__")
  6. if other is NotImplemented:
  7. return other
  8. self, other = self._normalize_two_args(self, other)
  9. res = self._array.__add__(other._array)
  10. return self.__class__._new(res)

字符串

svdrlsy4

svdrlsy41#

方法__add__被称为dunder(“双下划线”)或魔术方法。__add__用于为任何类的+操作符定义行为,而不仅仅是在Numpy中,并且您不需要做任何特殊的事情来使+触发__add__
几乎所有的操作员都有类似的神奇方法。
来自Python文档(https://docs.python.org/3/reference/datamodel.html#object.%5F%5Fadd%5F%5F):
要计算表达式x + y,其中x是具有__add__()方法的类的示例,类型(x).add(x,y)被调用。

g52tjvyc

g52tjvyc2#

Python运算符重载和Python数据模型是可以让你更清楚一点的主题。
更简洁地说,当你调用one_thing + another_thing时,python解释器会调用one_thing.__add__(another_thing),但是如果one_thing没有实现__add__,解释器会尝试another_thing.__radd__(one_thing)。否则你会得到一个Exception。
当然,你可以实现你自己版本的__add__方法,当你这样做的时候,你的对象就能够处理“+”加运算符了,这就是你的问题的例子中发生的事情。
下面你可以看到这样的例子:

ryevplcw

ryevplcw3#

看看NDArrayOperatorsMixin,特别是这里。它说它使用array_ufunc。这是它如何将运算符Map到方法。此外,请看这里和这里以及这里,看看它实际上是如何处理的。如果你想有更深入的了解,那么你需要自己调试。
以下是截至2023年11月18日的mixins.py的原始代码:

  1. """Mixin classes for custom array types that don't inherit from ndarray."""
  2. from numpy._core import umath as um
  3. __all__ = ['NDArrayOperatorsMixin']
  4. def _disables_array_ufunc(obj):
  5. """True when __array_ufunc__ is set to None."""
  6. try:
  7. return obj.__array_ufunc__ is None
  8. except AttributeError:
  9. return False
  10. def _binary_method(ufunc, name):
  11. """Implement a forward binary method with a ufunc, e.g., __add__."""
  12. def func(self, other):
  13. if _disables_array_ufunc(other):
  14. return NotImplemented
  15. return ufunc(self, other)
  16. func.__name__ = '__{}__'.format(name)
  17. return func
  18. def _reflected_binary_method(ufunc, name):
  19. """Implement a reflected binary method with a ufunc, e.g., __radd__."""
  20. def func(self, other):
  21. if _disables_array_ufunc(other):
  22. return NotImplemented
  23. return ufunc(other, self)
  24. func.__name__ = '__r{}__'.format(name)
  25. return func
  26. def _inplace_binary_method(ufunc, name):
  27. """Implement an in-place binary method with a ufunc, e.g., __iadd__."""
  28. def func(self, other):
  29. return ufunc(self, other, out=(self,))
  30. func.__name__ = '__i{}__'.format(name)
  31. return func
  32. def _numeric_methods(ufunc, name):
  33. """Implement forward, reflected and inplace binary methods with a ufunc."""
  34. return (_binary_method(ufunc, name),
  35. _reflected_binary_method(ufunc, name),
  36. _inplace_binary_method(ufunc, name))
  37. def _unary_method(ufunc, name):
  38. """Implement a unary special method with a ufunc."""
  39. def func(self):
  40. return ufunc(self)
  41. func.__name__ = '__{}__'.format(name)
  42. return func
  43. class NDArrayOperatorsMixin:
  44. """Mixin defining all operator special methods using __array_ufunc__.
  45. This class implements the special methods for almost all of Python's
  46. builtin operators defined in the `operator` module, including comparisons
  47. (``==``, ``>``, etc.) and arithmetic (``+``, ``*``, ``-``, etc.), by
  48. deferring to the ``__array_ufunc__`` method, which subclasses must
  49. implement.
  50. It is useful for writing classes that do not inherit from `numpy.ndarray`,
  51. but that should support arithmetic and numpy universal functions like
  52. arrays as described in `A Mechanism for Overriding Ufuncs
  53. <https://numpy.org/neps/nep-0013-ufunc-overrides.html>`_.
  54. As an trivial example, consider this implementation of an ``ArrayLike``
  55. class that simply wraps a NumPy array and ensures that the result of any
  56. arithmetic operation is also an ``ArrayLike`` object::
  57. class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin):
  58. def __init__(self, value):
  59. self.value = np.asarray(value)
  60. # One might also consider adding the built-in list type to this
  61. # list, to support operations like np.add(array_like, list)
  62. _HANDLED_TYPES = (np.ndarray, numbers.Number)
  63. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  64. out = kwargs.get('out', ())
  65. for x in inputs + out:
  66. # Only support operations with instances of _HANDLED_TYPES.
  67. # Use ArrayLike instead of type(self) for isinstance to
  68. # allow subclasses that don't override __array_ufunc__ to
  69. # handle ArrayLike objects.
  70. if not isinstance(x, self._HANDLED_TYPES + (ArrayLike,)):
  71. return NotImplemented
  72. # Defer to the implementation of the ufunc on unwrapped values.
  73. inputs = tuple(x.value if isinstance(x, ArrayLike) else x
  74. for x in inputs)
  75. if out:
  76. kwargs['out'] = tuple(
  77. x.value if isinstance(x, ArrayLike) else x
  78. for x in out)
  79. result = getattr(ufunc, method)(*inputs, **kwargs)
  80. if type(result) is tuple:
  81. # multiple return values
  82. return tuple(type(self)(x) for x in result)
  83. elif method == 'at':
  84. # no return value
  85. return None
  86. else:
  87. # one return value
  88. return type(self)(result)
  89. def __repr__(self):
  90. return '%s(%r)' % (type(self).__name__, self.value)
  91. In interactions between ``ArrayLike`` objects and numbers or numpy arrays,
  92. the result is always another ``ArrayLike``:
  93. >>> x = ArrayLike([1, 2, 3])
  94. >>> x - 1
  95. ArrayLike(array([0, 1, 2]))
  96. >>> 1 - x
  97. ArrayLike(array([ 0, -1, -2]))
  98. >>> np.arange(3) - x
  99. ArrayLike(array([-1, -1, -1]))
  100. >>> x - np.arange(3)
  101. ArrayLike(array([1, 1, 1]))
  102. Note that unlike ``numpy.ndarray``, ``ArrayLike`` does not allow operations
  103. with arbitrary, unrecognized types. This ensures that interactions with
  104. ArrayLike preserve a well-defined casting hierarchy.
  105. .. versionadded:: 1.13
  106. """
  107. __slots__ = ()
  108. # Like np.ndarray, this mixin class implements "Option 1" from the ufunc
  109. # overrides NEP.
  110. # comparisons don't have reflected and in-place versions
  111. __lt__ = _binary_method(um.less, 'lt')
  112. __le__ = _binary_method(um.less_equal, 'le')
  113. __eq__ = _binary_method(um.equal, 'eq')
  114. __ne__ = _binary_method(um.not_equal, 'ne')
  115. __gt__ = _binary_method(um.greater, 'gt')
  116. __ge__ = _binary_method(um.greater_equal, 'ge')
  117. # numeric methods
  118. __add__, __radd__, __iadd__ = _numeric_methods(um.add, 'add')
  119. __sub__, __rsub__, __isub__ = _numeric_methods(um.subtract, 'sub')
  120. __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul')
  121. __matmul__, __rmatmul__, __imatmul__ = _numeric_methods(
  122. um.matmul, 'matmul')
  123. # Python 3 does not use __div__, __rdiv__, or __idiv__
  124. __truediv__, __rtruediv__, __itruediv__ = _numeric_methods(
  125. um.true_divide, 'truediv')
  126. __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods(
  127. um.floor_divide, 'floordiv')
  128. __mod__, __rmod__, __imod__ = _numeric_methods(um.remainder, 'mod')
  129. __divmod__ = _binary_method(um.divmod, 'divmod')
  130. __rdivmod__ = _reflected_binary_method(um.divmod, 'divmod')
  131. # __idivmod__ does not exist
  132. # TODO: handle the optional third argument for __pow__?
  133. __pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow')
  134. __lshift__, __rlshift__, __ilshift__ = _numeric_methods(
  135. um.left_shift, 'lshift')
  136. __rshift__, __rrshift__, __irshift__ = _numeric_methods(
  137. um.right_shift, 'rshift')
  138. __and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and, 'and')
  139. __xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor, 'xor')
  140. __or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or, 'or')
  141. # unary methods
  142. __neg__ = _unary_method(um.negative, 'neg')
  143. __pos__ = _unary_method(um.positive, 'pos')
  144. __abs__ = _unary_method(um.absolute, 'abs')
  145. __invert__ = _unary_method(um.invert, 'invert')

字符串

展开查看全部

相关问题