Python错误汇总(转)

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  1. >>> def f(x, y, z):  
  2.     return x + y + z  
  3.   
  4. >>> args = (1,2,3)  
  5. >>> print f(args)  
  6.   
  7. Traceback (most recent call last):  
  8.   File "<pyshell#6>", line 1in <module>  
  9.     print f(args)  
  10. TypeError: f() takes exactly 3 arguments (1 given)  
错误分析 】args是一个元祖,如果是f(args),那么元祖是作为一个整体作为一个参数

*args,才是将元祖中的每个元素作为参数

  1. >>> f(*args)  
  2. 6  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  1. >>> def f(a,b,c,d):  
  2. ...   print a,b,c,d  
  3. ...  
  4. >>> args = (1,2,3,4)  
  5. >>> f(**args)  
  6. Traceback (most recent call last):  
  7.   File "<stdin>", line 1in <module>  
  8. TypeError: f() argument after ** must be a mapping, not tuple  

错误分析】错误原因**匹配并收集在字典中所有包含位置的参数,但传递进去的却是个元祖。

所以修改传递参数如下:

  1. >>> args = {'a':1,'b':2,'c':3}  
  2. >>> args['d'] = 4  
  3. >>> f(**args)  
  4. 1 2 3 4  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


错误分析】在函数hider()内使用了内置变量open,但根据Python作用域规则LEGB的优先级:

先是查找本地变量==》模块内的其他函数==》全局变量==》内置变量,查到了即停止查找。

所以open在这里只是个字符串,不能作为打开文件来使用,所以报错,更改变量名即可。

可以导入__builtin__模块看到所有内置变量:异常错误、和内置方法

>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError',..

  .........................................zip,filter,map]

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  1. In [105]: T1 = (1)  
  2. In [106]: T2 = (2,3)  
  3. In [107]: T1 + T2  
  4. ---------------------------------------------------------------------------  
  5. TypeError                                 Traceback (most recent call last)  
  6. <ipython-input-107-b105c7b32d90> in <module>()  
  7. ----> 1 T1 + T2;  
  8.   
  9. TypeError: unsupported operand type(s) for +: 'int' and 'tuple'  
错误分析】(1)的类型是整数,所以不能与另一个元祖做合并操作,如果只有一个元素的元祖,应该用(1,)来表示

  1. In [108]: type(T1)  
  2. Out[108]: int  
  3.   
  4. In [109]: T1 = (1,)  
  5. In [110]: T2 = (2,3)  
  6. In [111]: T1 + T2  
  7. Out[111]: (123)  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  1. >>> hash(1,(2,[3,4]))  
  2.   
  3. Traceback (most recent call last):  
  4.   File "<pyshell#95>", line 1in <module>  
  5.     hash((1,2,(2,[3,4])))  
  6. TypeError: unhashable type: 'list'  

错误分析】字典中的键必须是不可变对象,如(整数,浮点数,字符串,元祖).

可用hash()判断某个对象是否可哈希

  1. >>> hash('string')  
  2. -1542666171  

但列表中元素是可变对象,所以是不可哈希的,所以会报上面的错误.

如果要用列表作为字典中的键,最简单的办法是:

  1. >>> D = {}  
  2. >>> D[tuple([3,4])] = 5  
  3. >>> D  
  4. {(34): 5}  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> L = [2,1,4,3]  
  2. >>> L.reverse().sort()  
  3. Traceback (most recent call last):  
  4.   File "<stdin>", line 1in <module>  
  5. AttributeError: 'NoneType' object has no attribute 'sort'  
  6. >>> L  
  7. [3412]  

错误分析】列表属于可变对象,其append(),sort(),reverse()会在原处修改对象,不会有返回值,

或者说返回值为空,所以要实现反转并排序,不能并行操作,要分开来写

  1. >>> L = [2,1,4,3]  
  2. >>> L.reverse()  
  3. >>> L.sort()  
  4. >>> L  
  5. [1234]  

或者用下面的方法实现:

  1. In [103]: sorted(reversed([2,1,4,3]))  
  2. Out[103]: [1234]  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  1. >>> class = 78  
  2. SyntaxError: invalid syntax  
错误分析】class是Python保留字,Python保留字不能做变量名,可以用Class,或klass
同样,保留字不能作为模块名来导入,比如说,有个and.py,但不能将其作为模块导入

  1. >>> import and  
  2. SyntaxError: invalid syntax  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> f = open('D:\new\text.data','r')  
  2. Traceback (most recent call last):  
  3.   File "<stdin>", line 1in <module>  
  4. IOError: [Errno 22] invalid mode ('r'or filename: 'D:\new\text.data'  
  5. >>> f = open(r'D:\new\text.data','r')  
  6. >>> f.read()  
  7. 'Very\ngood\naaaaa'  

错误分析】\n默认为换行,\t默认为TAB键.

所以在D:\目录下找不到ew目录下的ext.data文件,将其改为raw方式输入即可。

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. try:  
  2.     print 1 / 0  
  3.       
  4. except ZeroDivisionError:  
  5.     print 'integer division or modulo by zero'  
  6.       
  7. finally:  
  8.     print 'Done'  
  9.   
  10. else:    
  11.     print 'Continue Handle other part'  
  12. 报错如下:  
  13. D:\>python Learn.py  
  14.   File "Learn.py", line 11  
  15.     else:  
  16.        ^  
  17. SyntaxError: invalid syntax  

错误分析】错误原因,else, finally执行位置;正确的程序应该如下:

  1. try:  
  2.     print 1 / 0  
  3.       
  4. except ZeroDivisionError:  
  5.     print 'integer division or modulo by zero'  
  6.   
  7.   
  8. else:    
  9.     print 'Continue Handle other part'  
  10.       
  11. finally:  
  12.     print 'Done'  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  1. >>> [x,y for x in range(2for y in range(3)]  
  2.   File "<stdin>", line 1  
  3.     [x,y for x in range(2for y in range(3)]  
  4.            ^  
  5. SyntaxError: invalid syntax  
错误分析错误原因,列表解析中,x,y必须以数组的方式列出(x,y)
  1. >>> [(x,y) for x in range(2for y in range(3)]  
  2. [(00), (01), (02), (10), (11), (12)]  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. class JustCounter:  
  2.     __secretCount = 0  
  3.   
  4.     def count(self):  
  5.         self.__secretCount += 1  
  6.         print 'secretCount is:'self.__secretCount  
  7.   
  8. count1 = JustCounter()  
  9.   
  10. count1.count()  
  11. count1.count()  
  12.   
  13. count1.__secretCount  
报错如下:
  1. >>>   
  2. secretCount is1  
  3. secretCount is2  
  4.   
  5.   
  6. Traceback (most recent call last):  
  7.   File "D:\Learn\Python\Learn.py", line 13in <module>  
  8.     count1.__secretCount  
  9. AttributeError: JustCounter instance has no attribute '__secretCount'      

错误分析双下划线的类属性__secretCount不可访问,所以会报无此属性的错误. 

解决办法如下:

  1. # 1. 可以通过其内部成员方法访问  
  2. # 2. 也可以通过访问  
  3. ClassName._ClassName__Attr  
  4. #或   
  5. ClassInstance._ClassName__Attr  
  6. #来访问,比如:  
  7. print count1._JustCounter__secretCount  
  8. print JustCounter._JustCounter__secretCount   
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> print x  
  2. Traceback (most recent call last):  
  3.   File "<stdin>", line 1in <module>  
  4. NameError: name 'x' is not defined  
  5. >>> x = 1  
  6. >>> print x  
  7. 1  
错误分析】Python不允许使用未赋值变量
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> t = (1,2)  
  2. >>> t.append(3)  
  3. Traceback (most recent call last):  
  4.   File "<stdin>", line 1in <module>  
  5. AttributeError: 'tuple' object has no attribute 'append'  
  6. >>> t.remove(2)  
  7. Traceback (most recent call last):  
  8.   File "<stdin>", line 1in <module>  
  9. AttributeError: 'tuple' object has no attribute 'remove'  
  10. >>> t.pop()  
  11. Traceback (most recent call last):  
  12.   File "<stdin>", line 1in <module>  
  13. AttributeError: 'tuple' object has no attribute 'pop'  
错误分析】属性错误,归根到底在于元祖是不可变类型,所以没有这几种方法.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> t = ()  
  2. >>> t[0]  
  3. Traceback (most recent call last):  
  4.   File "<stdin>", line 1in <module>  
  5. IndexError: tuple index out of range  
  6. >>> l = []  
  7. >>> l[0]  
  8. Traceback (most recent call last):  
  9.   File "<stdin>", line 1in <module>  
  10. IndexError: list index out of range  
错误分析】空元祖和空列表,没有索引为0的项
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> if X>Y:  
  2. ...  X,Y = 3,4  
  3. ...   print X,Y  
  4.   File "<stdin>", line 3  
  5.     print X,Y  
  6.     ^  
  7. IndentationError: unexpected indent  
  8.   
  9.   
  10. >>>   t = (1,2,3,4)  
  11.   File "<stdin>", line 1  
  12.     t = (1,2,3,4)  
  13.     ^  
  14. IndentationError: unexpected indent  
错误分析】一般出在代码缩进的问题
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> f = file('1.txt')  
  2. >>> f.readline()  
  3. 'AAAAA\n'  
  4. >>> f.readline()  
  5. 'BBBBB\n'  
  6. >>> f.next()  
  7. 'CCCCC\n'  
错误分析】如果文件里面没有行了会报这种异常
  1. >>> f.next() #  
  2. Traceback (most recent call last):  
  3.   File "<stdin>", line 1in <module>  
  4. StopIteration  

有可迭代的对象的next方法,会前进到下一个结果,而在一系列结果的末尾时,会引发StopIteration的异常.

next()方法属于Python的魔法方法,这种方法的效果就是:逐行读取文本文件的最佳方式就是根本不要去读取。

取而代之的用for循环去遍历文件,自动调用next()去调用每一行,且不会报错

  1. for line in open('test.txt','r'):  
  2.     print line  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  1. >>> string = 'SPAM'  
  2. >>> a,b,c = string  
  3. Traceback (most recent call last):  
  4.   File "<stdin>", line 1in <module>  
  5. ValueError: too many values to unpack  
错误分析】接受的变量少了,应该是
  1. >>> a,b,c,d = string  
  2. >>> a,d  
  3. ('S''M')  
  4. #除非用切片的方式  
  5. >>> a,b,c = string[0],string[1],string[2:]  
  6. >>> a,b,c  
  7. ('S''P''AM')  
  8. 或者  
  9. >>> a,b,c = list(string[:2]) + [string[2:]]  
  10. >>> a,b,c  
  11. ('S''P''AM')  
  12. 或者  
  13. >>> (a,b),c = string[:2],string[2:]  
  14. >>> a,b,c  
  15. ('S''P''AM')  
  16. 或者  
  17. >>> ((a,b),c) = ('SP','AM')  
  18. >>> a,b,c  
  19. ('S''P''AM')  
  20.   
  21. 简单点就是:  
  22. >>> a,b = string[:2]  
  23. >>> c   = string[2:]  
  24. >>> a,b,c  
  25. ('S''P''AM')  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> mydic={'a':1,'b':2}  
  2. >>> mydic['a']  
  3. 1  
  4. >>> mydic['c']  
  5. Traceback (most recent call last):  
  6.   File "<stdin>", line 1in ?  
  7. KeyError: 'c'  
错误分析】当映射到字典中的键不存在时候,就会触发此类异常, 或者可以,这样测试

  1. >>> 'a' in mydic.keys()  
  2. True  
  3. >>> 'c' in mydic.keys()              #用in做成员归属测试  
  4. False  
  5. >>> D.get('c','"c" is not exist!')   #用get或获取键,如不存在,会打印后面给出的错误信息  
  6. '"c" is not exist!'  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. File "study.py", line 3  
  2.   return None  
  3.   ^  
  4. dentationError: unexpected indent  
错误分析】一般是代码缩进问题,TAB键或空格键不一致导致

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  1. >>>def A():  
  2. return A()  
  3. >>>A() #无限循环,等消耗掉所有内存资源后,报最大递归深度的错误    
  4. File "<pyshell#2>", line 2in A return A()RuntimeError: maximum recursion depth exceeded  
  5. class Bird:  
  6.     def __init__(self):  
  7.         self.hungry = True  
  8.     def eat(self):  
  9.         if self.hungry:  
  10.             print "Ahaha..."  
  11.             self.hungry = False  
  12.         else:  
  13.             print "No, Thanks!"  
  14. 该类定义鸟的基本功能吃,吃饱了就不再吃  
  15. 输出结果:  
  16. >>> b = Bird()  
  17. >>> b.eat()  
  18. Ahaha...  
  19. >>> b.eat()  
  20. No, Thanks!  
  21. 下面一个子类SingBird,  
  22. class SingBird(Bird):  
  23.     def __init__(self):  
  24.         self.sound = 'squawk'  
  25.     def sing(self):  
  26.         print self.sound  
  27. 输出结果:  
  28. >>> s = SingBird()  
  29. >>> s.sing()  
  30. squawk  
  31. SingBird是Bird的子类,但如果调用Bird类的eat()方法时,  
  32. >>> s.eat()  
  33. Traceback (most recent call last):  
  34.   File "<pyshell#5>", line 1in <module>  
  35.     s.eat()  
  36.   File "D:\Learn\Python\Person.py", line 42in eat  
  37.     if self.hungry:  
  38. AttributeError: SingBird instance has no attribute 'hungry'  
错误分析】代码错误很清晰,SingBird中初始化代码被重写,但没有任何初始化hungry的代码
  1. class SingBird(Bird):  
  2.     def __init__(self):  
  3.         self.sound = 'squawk'  
  4.         self.hungry = Ture #加这么一句  
  5.     def sing(self):  
  6.         print self.sound  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. class Bird:  
  2.     def __init__(self):  
  3.         self.hungry = True  
  4.     def eat(self):  
  5.         if self.hungry:  
  6.             print "Ahaha..."  
  7.             self.hungry = False  
  8.         else:  
  9.             print "No, Thanks!"  
  10.   
  11. class SingBird(Bird):  
  12.     def __init__(self):  
  13.         super(SingBird,self).__init__()  
  14.         self.sound = 'squawk'  
  15.     def sing(self):  
  16.         print self.sound  
  17. >>> sb = SingBird()  
  18. Traceback (most recent call last):  
  19.   File "<pyshell#5>", line 1in <module>  
  20.     sb = SingBird()  
  21.   File "D:\Learn\Python\Person.py", line 51in __init__  
  22.     super(SingBird,self).__init__()  
  23. TypeError: must be type, not classobj  
错误分析】在模块首行里面加上__metaclass__=type,具体还没搞清楚为什么要加
  1. __metaclass__=type  
  2. class Bird:  
  3.     def __init__(self):  
  4.         self.hungry = True  
  5.     def eat(self):  
  6.         if self.hungry:  
  7.             print "Ahaha..."  
  8.             self.hungry = False  
  9.         else:  
  10.             print "No, Thanks!"  
  11.   
  12. class SingBird(Bird):  
  13.     def __init__(self):  
  14.         super(SingBird,self).__init__()  
  15.         self.sound = 'squawk'  
  16.     def sing(self):  
  17.         print self.sound  
  18. >>> S = SingBird()  
  19. >>> S.  
  20. SyntaxError: invalid syntax  
  21. >>> S.  
  22. SyntaxError: invalid syntax  
  23. >>> S.eat()  
  24. Ahaha...  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> T  
  2. (1234)  
  3. >>> T[0] = 22   
  4. Traceback (most recent call last):  
  5.   File "<pyshell#129>", line 1in <module>  
  6.     T[0] = 22  
  7. TypeError: 'tuple' object does not support item assignment  
错误分析】元祖不可变,所以不可以更改;可以用切片或合并的方式达到目的.
  1. >>> T = (1,2,3,4)  
  2. >>> (22,) + T[1:]  
  3. (22234)  
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1. >>> X = 1;  
  2. >>> Y = 2;  
  3. >>> X + = Y  
  4.   File "<stdin>", line 1  
  5.     X + = Y  
  6.         ^  
  7. SyntaxError: invalid syntax  

错误分析】增强行赋值不能分开来写,必须连着写比如说 +=, *=

  1. >>> X += Y  
  2. >>> X;Y  
  3. 3  
  4. 2  

转载:Python错误汇总 ,写的真好啊。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值