python机器学习实战3.2提示错误AttributeError: type object 'str' has no attribute '_name_'
2017-09-27 19:29
1096 查看
在做《Machine Learning in Action》书中的第三章绘制树形图时遇到了这个问题AttributeError: type object 'str' has no attribute '_name_'
很明显是if type(secondDict[key])._name_ == ‘dict’:这一句有问题,在python2(我使用的python2.7)中并没有type(secondDict[key])._name_这样的用法
所以我们要将源代码中的_name_去掉,变成if type(secondDict[key]) == ‘dict’:但这时我们会发现新的问题,编译确实没有报错,但是结果却和我们想要的结果不一样
我们很容易知道叶子节点的数目为3,但我们得出的结果却是2,这是怎么回事呢?我们再回到源码中看
if type(secondDict[key]) == ‘dict’:
这一句中的'dict'加了引号,这就是问题所在了,我们这句判断的语句本来是判断该节点类型是否为dict(字典),但是现在却成了判断该节点类型和‘dict'的类型是否相同,很明显'dict'的类型为string类型,故而,我们本来是想求得一颗树中的叶子节点的数目,现在却变成了求树节点中除叶子节点的其他节点的数目。故而输出2
现在我们知道问题所在,修改就简单了。两种改法:
if type(secondDict[key]) == dict:
或者if type(secondDict[key]) is dict:
再测试下,成功!
很明显是if type(secondDict[key])._name_ == ‘dict’:这一句有问题,在python2(我使用的python2.7)中并没有type(secondDict[key])._name_这样的用法
所以我们要将源代码中的_name_去掉,变成if type(secondDict[key]) == ‘dict’:但这时我们会发现新的问题,编译确实没有报错,但是结果却和我们想要的结果不一样
我们很容易知道叶子节点的数目为3,但我们得出的结果却是2,这是怎么回事呢?我们再回到源码中看
if type(secondDict[key]) == ‘dict’:
这一句中的'dict'加了引号,这就是问题所在了,我们这句判断的语句本来是判断该节点类型是否为dict(字典),但是现在却成了判断该节点类型和‘dict'的类型是否相同,很明显'dict'的类型为string类型,故而,我们本来是想求得一颗树中的叶子节点的数目,现在却变成了求树节点中除叶子节点的其他节点的数目。故而输出2
现在我们知道问题所在,修改就简单了。两种改法:
if type(secondDict[key]) == dict:
或者if type(secondDict[key]) is dict:
再测试下,成功!
相关文章推荐
- python 提示错误AttributeError: type object 'str' has no attribute '_name_'
- python 编译错误TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
- python :TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
- 《python核心编程》序列:字符串、列表和元组Python: Attribute Error - 'NoneType' object has no attribute
- Python开发:AttributeError: 'Class_Of_LoanUseCase' object has no attribute '_type_equality_funcs'
- 执行Python程序时,报AttributeError: 'function' object has no attribute 'name'
- Python错误AttributeError: 'module' object has no attribute 'copy'
- Python3下错误AttributeError: ‘dict’ object has no attribute’iteritems‘的分析与解决
- python3.6报错:AttributeError: 'str' object has no attribute 'decode'
- python __def__ Exception AttributeError: "'NoneType' object has no attribute
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- [Python][转]Exception AttributeError: "'NoneType' object has no attribute
- Django 错误信息:AttributeError: 'str' object has no attribute '_meta'
- Django 错误信息:AttributeError: 'str' object has no attribute '_meta'
- python 错误解析 AttributeError: 'module' object has no attribute 'dumps'
- 【Python错误】AttributeError: 'bool' object has no attribute '__call__'
- [python错误]builtins.AttributeError: 'module' object has no attribute 'request'
- python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法
- Python报错——错误“AttributeError:'builtin_function_or_method' object has no attribute 'sleep'”
- python遇到AttributeError: 'str' object has no attribute '_getAssertEqualityFunc'问题解决过程