[Python] Custom numpy element type with arithmetic functions without overloading `np.ndarray`

Discussão em 'Python' iniciado por Stack, Agosto 30, 2025.

  1. Stack

    Stack Membro Participativo

    Is it possible to implement a custom class (say, class Foo) with __add__, __mul__, etc. methods defined and add it into a normal np.ndarray (np.asarray([Foo(1), Foo(2)])) and have numpy delegate to methods Foo.__add__/Foo.__mul__ when +/* operations are applied?

    Operations on custom types are usually achieved by providing __array_ufunc__ in the ndarray (or the array container which hold the array elements), but in my case, I don't have control over how the array elements (Foo) are used. They can be used as scalar (foo1 + foo2), assigned to an array (foo_array[:] = foo1 or np.asarray([foo1, foo2, ...]) or used for scalar/array operations (foo_array = foo_array + foo1, or foo_array1 + foo_array2). At the time of instantiating Foo, it's unknown how it will be used, but during an actual operation, other in def __add__(self, other) would be able to distinguish between those usage cases (scalar, array op).

    Now I understand that this can't be done usually as a + b would invoke the a.__add__(b) method and if a was an array of dtype=object with Foo instances, the __add__ call wouldn't necessarily delegated to Foo My question really is if there is some mechanism that does potentially delegate to Foo and what needs to be done (magic function definition?) to do so?

    It may be that I'm on the wrong track which would also be an insight and a valid answer ;-).

    Continue reading...

Compartilhe esta Página