欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AttributeError系列之:AttributeError: 'tuple' object has no attribute 'shape'

程序员文章站 2022-05-27 11:58:29
...

翻译:属性错误,tuple对象没有shape属性。

这往往发生在我们对一个tuple类型数据,调用成员变量shape所致(a.shape 或 a.shape[])。

所以要查看调用发生处,看看自己的数据类型是不是有错。我们看代码

import numpy as np

a = np.zeros([5,5])
#正确使用方式:
print(a)
print(type(a))
print(type(a.shape))
print(a.shape)
#出错:

a = tuple(a) #这段代码将a转换成了tuple类型

print(type(a))
print(type(a.shape))#报错
print(a.shape)#报错

仔细看代码中注释报错的地方均为错误用法!!

相似的报错有:

AttributeError: 'list' object has no attribute 'shape';

AttributeError: 'int' object has no attribute 'shape';

等,都是这样的原因,大家要注意!

PS:tuple(a),类型转换不会影响a的性质,必须要如果想保存转换后的变量必须,谁声明新的变量来保存,例 b = tuple(a).

b 就是 tuple型,而a类型不变。

与另一种错误区分:TypeError: 'tuple' object is not callable.

详见我的另一篇博客:https://blog.csdn.net/qq_41368074/article/details/105737846

相关标签: