Can I cast a python class to a numpy array?
from dataclasses import dataclass
import numpy as np
@dataclass
class X:
x: float = 0
y: float = 0
x = X()
x_array = np.array(x) # would like to get an numpy array np.array([X.x,X.y])
In the last step, I would like the to obtain an array np.array([X.x, X.y]). Instead, I get array(X(x=0, y=0), dtype=object).
Can I provide method for the dataclass so that the casting works as desired (or overload one of the existing methods of the dataclass)?
def __iter__(self): yield from (self.x, self.y)numpy.arrayit is clear that you can define__array__method likedef __array__(self): return np.array([self.x, self.y])