首先这是一个很简单的 运行时错误:
错误分析:
AttributeError:属性错误,造成这种错误的原因可能有:
- 你尝试访问一个不存在的属性或方法。检查一下拼写!你可以使用内建函数 dir 来列出存在的属性。
- 如果一个属性错误表明一个对象是 NoneType ,那意味着它就是 None 。因此问题不在于属性名,而在于对象本身。
对象是 None 的一个可能原因,是你忘记从函数返回一个值;如果程序执行到函数
的末尾没有碰到 return 语句,它就会返回 None 。另一个常见的原因是使用了列表
方法的结果,如 sort ,这种方法返回的是 None
我的原因是1:我使用了dict.encode()方法,但实际上dict对象并没encode方法。encode方法是属于str对象的。
由此可见我对encode 和 decode不够了解,对于调用他们的对象并不十分理解
encode编码--调用这个方法的对象是str类型
decode解码--调用这个方法的对象是bytes类型
他们都是关于字符对象(str&bytes)的方法,所以像下面这样,当a 是一个dict 字典类型的对象时,
调用encode()方法时就会报AttributeError: 'dict' object has no attribute 'encode',因为字典没有这个方法呀
1 In [1]: a = { "uid":"5171979","communityid":"338855","cityid":"16"} 2 3 In [2]: type(a) 4 Out[2]: dict 5 6 In [3]: a = a.encode("utf-8") 7 --------------------------------------------------------------------------- 8 AttributeError Traceback (most recent call last) 9 <ipython-input-3-e0edb4553e35> in <module> 10 ----> 1 a = a.encode("utf-8") 11 12 AttributeError: 'dict' object has no attribute 'encode'
解决的办法:把a这个dict对象转换为字符类型
通过第11行代码,可以看到,a可以encode成功了,b开头的字符串表示bytes类型
1 In [4]: a = str(a) 2 3 In [5]: type(a) 4 Out[5]: str 5 6 In [6]: a 7 Out[6]: "{'uid': '5171979', 'communityid': '338855', 'cityid': '16'}" 8 9 In [11]: b=a.encode("utf-8")
10 In [12]: b
11 Out[12]: b"{'uid': '5171979', 'communityid': '338855', 'cityid': '16'}"
In [13]: type(b)
Out[13]: bytes
In [13]: type(b)
Out[13]: bytes
附:
使用dir查看dict类型的所有属性,可以看到并没有encode和decode方法
1 In [8]: dir(dict) 2 Out[8]: 3 ['__class__', 4 '__contains__', 5 '__delattr__', 6 '__delitem__', 7 '__dir__', 8 '__doc__', 9 '__eq__', 10 '__format__', 11 '__ge__', 12 '__getattribute__', 13 '__getitem__', 14 '__gt__', 15 '__hash__', 16 '__init__', 17 '__init_subclass__'