使用np.array(list)在类__init__中转换List > numpy.ndarray不成功。numpy的问题?

0 投票
1 回答
32 浏览
提问于 2025-04-12 00:20

我现在正在创建一个叫做 'system' 的类,这个类需要接收四个参数:A, B, C, D,它们都是状态空间系统的矩阵。

这个类的目的是让用户可以使用嵌套的内置 <class 'list'> 类型来输入这些矩阵,比如 [[1, 0],[0, 1]]

类的 __init__ 方法应该接收这些列表,并使用 np.array() 将它们转换成 NumPy 数组,类型是 <class 'np.ndarray'>,然后把它们存储为 self.A, self.B 等等。

但是,在完成 np.array() 操作后,当我用 print(type(self.A)) 检查这些对象的类型时,控制台却显示 <class 'list'>

我不明白这是怎么回事,因为我明明把它们定义成了 NumPy 数组。我在网上搜索过,也问过 ChatGPT,但没有找到能解释这个问题的答案。这可能和 NumPy 有关吗?还是我对 Python 类构造函数的理解有问题?

我运行的脚本(所有变量都已清空) :

import numpy as np


class system():
    def __init__(self, A, B=None, C=None, D=None):
        self.A = np.array(A)
        self.B = np.array(B)
        self.C = np.array(C)
        self.D = np.array(D)

        print(type(A))

        assert self.A.shape[0] == self.A.shape[1], 'System matrix (A) not square'
        assert self.A.shape[0] == self.B.shape[0], 'Number of rows of A does not match number of rows of B'

    def fxKutta(self, X, U):

        X = np.array(X).reshape(-1, 1)
        U = np.array(U).reshape(-1, 1)

        assert X.shape[0] == self.A.shape[0], 'Number of rows of X does not match number of rows of A'
        assert U.shape[0] == self.B.shape[0], 'Number of rows of U does not match number of rows of B'

        Xdot = self.A @ X + self.B @ U

        return Xdot


A = [[1, 1], [1, 1]]
B = [[1], [1]]

sys = system(A, B)

运行后的控制台 :

<class 'list'>

#====================================================

我尝试通过另一个变量传递数组 :

def __init__(self, A, B=None, C=None, D=None):
        matA = np.array(A)
        A = np.array(matA)

... 但这也没有成功。反正这也不是个干净的解决方案。

1 个回答

0

你在检查传入的参数 A 的类型,这个参数是以列表的形式传给你的类的。如果你检查一下实例变量 self.A 的类型,结果会是 <class 'numpy.ndarray'>

撰写回答