类__init__中np.array转numpy.ndarray失败问题排查
问题分析与解决
你遇到的问题是打印对象错误:代码里print(type(A))打印的是传入的参数A(原始列表)的类型,而非转换后存储在实例属性里的self.A的类型。你原本的转换逻辑self.A = np.array(A)是正确的,self.A已经是np.ndarray类型,只是你没打印它而已。
修正步骤
- 修改打印语句,打印实例属性
self.A的类型:
print(type(self.A)) # 替换原来的 print(type(A))
- 运行修改后的代码,控制台会输出
<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
相关产品推荐
相关产品推荐

