问题描述:

Can anyone see a good way to solve the issue in title? It comes up when numpy does something silly for addition to my custom data type (as here) and I want to override its behavior

I found this in official docs for coercion rules, which says that it could be done if "b"'s class is subclass of numpy array type, but it's suboptimal because I don't want my type to subclass ndarray

网友答案:

Use the __array_priority__ attribute used by numpy to indicate your type has a higher priority. eg.

import numpy as np

class MyClass:

    __array_priority__ = 0

    def __init__(self, data):
        self.arr = np.array(data)

    def __array__(self):
        return self.arr

    def __radd__(self, other):
        return "MyClass radd"

a = np.array([1])
b = MyClass([2])

# low priority (or no priority), numpy array addition
assert isinstance(a + b, np.ndarray)

# higher priority, your addition
MyClass.__array_priority__ = 1
assert a + b == "MyClass radd"
网友答案:

It can be done with monkey-patching, something like:

old_add = np.ndarray.__add__

def new_add(self, other):
    if isinstance(other, MyType):
        return other.__radd__(self)
    else:
        return old_add(self, other)

np.ndarray.__add__ = new_add

This will normally throw an error can't set attributes of built-in/extension type 'numpy.ndarray'. According to this there is a workaround, I'll let you try it out yourself.

相关阅读:
Top