Python錯誤匯總,python匯總
開個貼,用於記錄平時經常碰到的Python的錯誤同時對導致錯誤的原因進行分析,並持續更新,方便以後查詢,學習。
知識在於積累嘛!
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In [105]: T1 = (1)In [106]: T2 = (2,3)In [107]: T1 + T2---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-107-b105c7b32d90> in <module>()----> 1 T1 + T2;TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
【錯誤分析】(1)的類型是整數,所以不能與另一個元祖做合併作業,如果只有一個元素的元祖,應該用
(1
,
)來表示
In [108]: type(T1)Out[108]: intIn [109]: T1 = (1,)In [110]: T2 = (2,3)In [111]: T1 + T2Out[111]: (1, 2, 3)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> hash(1,(2,[3,4]))Traceback (most recent call last): File "<pyshell#95>", line 1, in <module> hash((1,2,(2,[3,4])))TypeError: unhashable type: 'list'
【錯誤分析】字典中的鍵必須是不可變對象,如(整數,浮點數,字串,元祖),可用hash()判斷某個對象是否可雜湊
>>> hash('string')-1542666171
但列表中元素是可變對象,所以是不可雜湊的,所以會報上面的錯誤.如果要用列表作為字典中的鍵,最簡單的辦法是:
>>> D = {}>>> D[tuple([3,4])] = 5>>> D{(3, 4): 5}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> L = [2,1,4,3]>>> L.reverse().sort()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'NoneType' object has no attribute 'sort'>>> L[3, 4, 1, 2]
【錯誤分析】列表屬於可變對象,其append(),sort(),reverse()會在原處修改對象,不會有返回值,或者說返回值為空白,
所以要實現反轉並排序,不能並行操作,要分開來寫
>>> L = [2,1,4,3]>>> L.reverse()>>> L.sort()>>> L[1, 2, 3, 4]
或者用下面的方法實現:
In [103]: sorted(reversed([2,1,4,3]))Out[103]: [1, 2, 3, 4]
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> class = 78SyntaxError: invalid syntax
【錯誤分析】class是Python保留字,Python保留字不能做變數名,可以用Class,或klass
同樣,保留字不能作為模組名來匯入,比如說,有個and.py,但不能將其作為模組匯入
>>> import andSyntaxError: invalid syntax
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> f = open('D:\new\text.data','r')Traceback (most recent call last): File "<stdin>", line 1, in <module>IOError: [Errno 22] invalid mode ('r') or filename: 'D:\new\text.data'>>> f = open(r'D:\new\text.data','r')>>> f.read()'Very\ngood\naaaaa'
【錯誤分析】\n預設為換行,\t預設為TAB鍵,所以在D:\目錄下找不到ew目錄下的ext.data檔案,將其改為raw方式輸入即可。
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
try: print 1 / 0 except ZeroDivisionError: print 'integer division or modulo by zero' finally: print 'Done'else: print 'Continue Handle other part'報錯如下:D:\>python Learn.py File "Learn.py", line 11 else: ^SyntaxError: invalid syntax
【錯誤分析】錯誤原因,else, finally執行位置;正確的程式應該如下:
try: print 1 / 0 except ZeroDivisionError: print 'integer division or modulo by zero'else: print 'Continue Handle other part' finally: print 'Done'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> [x,y for x in range(2) for y in range(3)] File "<stdin>", line 1 [x,y for x in range(2) for y in range(3)] ^SyntaxError: invalid syntax
【錯誤分析】錯誤原因,列表解析中,x,y必須以數組的方式列出(x,y)
>>> [(x,y) for x in range(2) for y in range(3)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class JustCounter: __secretCount = 0 def count(self): self.__secretCount += 1 print 'secretCount is:', self.__secretCountcount1 = JustCounter()count1.count()count1.count()count1.__secretCount
報錯如下:
>>> secretCount is: 1secretCount is: 2Traceback (most recent call last): File "D:\Learn\Python\Learn.py", line 13, in <module> count1.__secretCountAttributeError: JustCounter instance has no attribute '__secretCount'
【錯誤分析】雙底線的類屬性__secretCount不可訪問,所以會報無此屬性的錯誤.
解決辦法如下:
# 1. 可以通過其內部成員方法訪問# 2. 也可以通過訪問ClassName._ClassName__Attr#或 ClassInstance._ClassName__Attr#來訪問,比如:print count1._JustCounter__secretCountprint JustCounter._JustCounter__secretCount
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> print xTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'x' is not defined>>> x = 1>>> print x1
【錯誤分析】Python不允許使用未賦值變數
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> t = (1,2)>>> t.append(3)Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'tuple' object has no attribute 'append'>>> t.remove(2)Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'tuple' object has no attribute 'remove'>>> t.pop()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'tuple' object has no attribute 'pop'
【錯誤分析】屬性錯誤,歸根到底在於元祖是不可變類型,所以沒有這幾種方法.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> t = ()>>> t[0]Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: tuple index out of range>>> l = []>>> l[0]Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: list index out of range
【錯誤分析】空元祖和空列表,沒有索引為0的項
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> if X>Y:... X,Y = 3,4... print X,Y File "<stdin>", line 3 print X,Y ^IndentationError: unexpected indent>>> t = (1,2,3,4) File "<stdin>", line 1 t = (1,2,3,4) ^IndentationError: unexpected indent
【錯誤分析】一般出在代碼縮排的問題
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> f = file('1.txt')>>> f.readline()'AAAAA\n'>>> f.readline()'BBBBB\n'>>> f.next()'CCCCC\n'
【錯誤分析】如果檔案裡面沒有行了會報這種異常
>>> f.next() #Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration
有可迭代的對象的next方法,會前進到下一個結果,而在一系列結果的末尾時,會引發StopIteration的異常.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> string = 'SPAM'>>> a,b,c = stringTraceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: too many values to unpack
【錯誤分析】接受的變數少了,應該是
>>> a,b,c,d = string>>> a,d('S', 'M')#除非用切片的方式>>> a,b,c = string[0],string[1],string[2:]>>> a,b,c('S', 'P', 'AM')或者>>> a,b,c = list(string[:2]) + [string[2:]]>>> a,b,c('S', 'P', 'AM')或者>>> (a,b),c = string[:2],string[2:]>>> a,b,c('S', 'P', 'AM')或者>>> ((a,b),c) = ('SP','AM')>>> a,b,c('S', 'P', 'AM')簡單點就是:>>> a,b = string[:2]>>> c = string[2:]>>> a,b,c('S', 'P', 'AM')
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> mydic={'a':1,'b':2}>>> mydic['a']1>>> mydic['c']Traceback (most recent call last): File "<stdin>", line 1, in ?KeyError: 'c'
【錯誤分析】當映射到字典中的鍵不存在時候,就會觸發此類異常, 或者可以,這樣測試
>>> 'a' in mydic.keys()True>>> 'c' in mydic.keys() #用in做成員歸屬測試False>>> D.get('c','"c" is not exist!') #用get或擷取鍵,如不存在,會列印後面給出的錯誤資訊'"c" is not exist!'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
File "study.py", line 3 return None ^IndentationError: unexpected indent
【錯誤分析】一般是代碼縮排問題,TAB鍵或空格鍵不一致導致
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>>def A():return A()>>>A() #無限迴圈,等消耗掉所有記憶體資源後,報最大遞迴深度的錯誤 File "<pyshell#2>", line 2, in A return A()RuntimeError: maximum recursion depth exceededclass Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print "Ahaha..." self.hungry = False else: print "No, Thanks!"該類定義鳥的準系統吃,吃飽了就不再吃輸出結果:>>> b = Bird()>>> b.eat()Ahaha...>>> b.eat()No, Thanks!下面一個子類SingBird,class SingBird(Bird): def __init__(self): self.sound = 'squawk' def sing(self): print self.sound輸出結果:>>> s = SingBird()>>> s.sing()squawkSingBird是Bird的子類,但如果調用Bird類的eat()方法時,>>> s.eat()Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> s.eat() File "D:\Learn\Python\Person.py", line 42, in eat if self.hungry:AttributeError: SingBird instance has no attribute 'hungry'
【錯誤分析】代碼錯誤很清晰,SingBird中初始化代碼被重寫,但沒有任何初始化hungry的代碼
class SingBird(Bird): def __init__(self): self.sound = 'squawk' self.hungry = Ture #加這麼一句 def sing(self): print self.sound
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print "Ahaha..." self.hungry = False else: print "No, Thanks!"class SingBird(Bird): def __init__(self): super(SingBird,self).__init__() self.sound = 'squawk' def sing(self): print self.sound>>> sb = SingBird()Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> sb = SingBird() File "D:\Learn\Python\Person.py", line 51, in __init__ super(SingBird,self).__init__()TypeError: must be type, not classobj
【錯誤分析】在模組首行裡面加上__metaclass__=type,具體還沒搞清楚為什麼要加
__metaclass__=typeclass Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print "Ahaha..." self.hungry = False else: print "No, Thanks!"class SingBird(Bird): def __init__(self): super(SingBird,self).__init__() self.sound = 'squawk' def sing(self): print self.sound>>> S = SingBird()>>> S.SyntaxError: invalid syntax>>> S.SyntaxError: invalid syntax>>> S.eat()Ahaha...
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> T(1, 2, 3, 4)>>> T[0] = 22 Traceback (most recent call last): File "<pyshell#129>", line 1, in <module> T[0] = 22TypeError: 'tuple' object does not support item assignment
【錯誤分析】元祖不可變,所以不可以更改;可以用切片或合并的方式達到目的.
>>> T = (1,2,3,4)>>> (22,) + T[1:](22, 2, 3, 4)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++