List > numpy.ndarray 使用 np.array(list) 在类 __init__ 中不起作用。 numpy 有问题吗?

问题描述 投票:0回答:1

我目前正在构建一个名为“

system
”的类,它接受 4 个参数:
A, B, C, D
,它们是状态空间系统的矩阵。

目的是用户可以使用嵌套的内置

<class 'list'>
类型输入这些内容,例如
[[1, 0],[0, 1]]

该类的

__init__
方法应获取这些列表,并使用
<class 'np.ndarray'>
将它们转换为
np.array()
类型的 NumPy 数组,并将它们存储为
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)

...这不起作用。无论如何,这都不是一个干净的解决方案。

python list numpy-ndarray init self
1个回答
0
投票

您正在检查传递的参数的类型

A
,在这种情况下,您将其作为列表传递到类中。如果您检查实例变量的类型,在本例中为
self.A
,结果将是
<class 'numpy.ndarray'>

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.