将 Python class 投射到 Numpy 数组

Cast a Python class to Numpy Array

我可以将 python class 转换为 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])

在最后一步,我想获得一个数组np.array([X.x, X.y])。相反,我得到 array(X(x=0, y=0), dtype=object).

我能否为 dataclass 提供方法,以便按需要进行转换(或重载 dataclass 的现有方法之一)?

docstring of numpy.array我们可以看到对第一个参数的要求

object: array_like

An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.

所以我们可以定义一个__array__方法,比如

@dataclass
class X:
    x: float = 0
    y: float = 0

    def __array__(self) -> np.ndarray:
        return np.array([self.x, self.y])

它将被np.array使用。我猜这应该适用于任何自定义 Python class。