You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类__init__中np.array转numpy.ndarray失败问题排查

问题分析与解决

你遇到的问题是打印对象错误:代码里print(type(A))打印的是传入的参数A(原始列表)的类型,而非转换后存储在实例属性里的self.A的类型。你原本的转换逻辑self.A = np.array(A)是正确的,self.A已经是np.ndarray类型,只是你没打印它而已。

修正步骤

  1. 修改打印语句,打印实例属性self.A的类型:
print(type(self.A))  # 替换原来的 print(type(A))
  1. 运行修改后的代码,控制台会输出<class 'numpy.ndarray'>,证明转换成功。

为什么你的尝试无效

你尝试的中间变量代码:

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

只是重新赋值了局部变量A,并没有对实例属性self.A做任何操作,所以完全不影响self.A的类型,自然无法解决问题。

验证代码

修正后的完整代码:

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(self.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 'numpy.ndarray'>

内容的提问来源于stack exchange,提问作者IsaacB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:05:17