錯誤:
>>> def f(x, y):
print x, y
>>> t = ('a', 'b')
>>> f(t)
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
f(t)
TypeError: f() takes exactly 2 arguments (1 given)
【錯誤分析】不要誤以為元祖里有兩個參數,將元祖傳進去就可以了,實際上元祖作為一個整體只是一個參數,
實際需要兩個參數,所以報錯。必需再傳一個參數方可.
>>> f(t, 'var2')
('a', 'b') var2
更常用的用法: 在前面加*,代表引用元祖
>>> f(*t)
'a', 'b'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
錯誤:
>>> def func(y=2, x):
return x + y
SyntaxError: non-default argument follows default argument
【錯誤分析】在C++,Python中默認參數從左往右防止,而不是相反。這可能跟參數進棧順序有關。
>>> def func(x, y=2):
return x + y
>>> func(1)
3
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
錯誤:
>>> D1 = {'x':1, 'y':2}
>>> D1['x']
1
>>> D1['z']
Traceback (most recent call last):
File "<pyshell#185>", line 1, in <module>
D1['z']
KeyError: 'z'
【錯誤分析】這是Python中字典鍵錯誤的提示,如果想讓程序繼續運行,可以用字典中的get方法,如果鍵存在,則獲取該鍵對應的值,不存在的,返回None,也可打印提示信息.
>>> D1.get('z', 'Key Not Exist!')
'Key Not Exist!'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
錯誤:
>>> from math import sqrt
>>> exec "sqrt = 1"
>>> sqrt(4)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
sqrt(4)
TypeError: 'int' object is not callable
【錯誤分析】exec語句最有用的地方在於動態地創建代碼字符串,但里面存在的潛在的風險,它會執行其他地方的字符串,在CGI中更是如此!比如例子中的sqrt = 1,從而改變了當前的命名空間,從math模塊中導入的sqrt不再和函數名綁定而是成為了一個整數。要避免這種情況,可以通過增加in <scope>,其中<scope>就是起到放置代碼字符串命名空間的字典。
>>> from math import sqrt
>>> scope = {}
>>> exec "sqrt = 1" in scope
>>> sqrt(4)
2.0
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
錯誤:
>>> seq = [1, 2, 3, 4]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
sep.join(seq)
TypeError: sequence item 0: expected string, int found
【錯誤分析】join是split的逆方法,是非常重要的字符串方法,但不能用來連接整數型列表,所以需要改成:
>>> seq = ['1', '2', '3', '4']
>>> sep = '+'
>>> sep.join(seq)
'1+2+3+4'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
錯誤:
>>> print r'C:\Program Files\foo\bar\'
SyntaxError: EOL while scanning string literal
【錯誤分析】Python中原始字符串以r開頭,里面可以放置任意原始字符,包括\,包含在字符中的\不做轉義。
但是,不能放在末尾!也就是說,最后一個字符不能是\,如果真 需要的話,可以這樣寫:
>>> print r'C:\Program Files\foo\bar' "\\"
C:\Program Files\foo\bar\
>>> print r'C:\Program Files\foo\bar' + "\\"
C:\Program Files\foo\bar\
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
代碼:
bad = 'bad'
try:
raise bad
except bad:
print 'Got Bad!'
錯誤:
>>>
Traceback (most recent call last):
File "D:\Learn\Python\Learn.py", line 4, in <module>
raise bad
TypeError: exceptions must be old-style classes or derived from BaseException, not str
【錯誤分析】因所用的Python版本2.7,比較高的版本,raise觸發的異常,只能是自定義類異常,而不能是字符串。所以會報錯,字符串改為自定義類,就可以了。
class Bad(Exception):
pass
def raiseException():
raise Bad()
try:
raiseException()
except Bad:
print 'Got Bad!'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class Super:
def method(self):
print "Super's method"
class Sub(Super):
def method(self):
print "Sub's method"
Super.method()
print "Over..."
S = Sub()
S.method()
執行上面一段代碼,錯誤如下:
>>>
Sub's method
Traceback (most recent call last):
File "D:\Learn\Python\test.py", line 12, in <module>
S.method()
File "D:\Learn\Python\test.py", line 8, in method
Super.method()
TypeError: unbound method method() must be called with Super instance as first argument (got nothing instead)
【錯誤分析】Python中調用類的方法,必須與實例綁定,或者調用自身.
ClassName.method(x, 'Parm')
ClassName.method(self)
所以上面代碼,要調用Super類的話,只需要加個self參數即可。
class Super:
def method(self):
print "Super's method"
class Sub(Super):
def method(self):
print "Sub's method"
Super.method(self)
print "Over..."
S = Sub()
S.method()
#輸出結果
>>>
Sub's method
Super's method
Over...
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> reload(sys)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
【錯誤分析】reload期望得到的是對象,所以該模塊必須成功導入。在沒導入模塊前,不能重載.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> def f(x, y, z):
return x + y + z
>>> args = (1,2,3)
>>> print f(args)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print f(args)
TypeError: f() takes exactly 3 arguments (1 given)
【錯誤分析】args是一個元祖,如果是f(args),那么元祖是作為一個整體作為一個參數
*args,才是將元祖中的每個元素作為參數
>>> f(*args)
6
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> def f(a,b,c,d):
... print a,b,c,d
...
>>> args = (1,2,3,4)
>>> f(**args)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() argument after ** must be a mapping, not tuple
【錯誤分析】錯誤原因**匹配並收集在字典中所有包含位置的參數,但傳遞進去的卻是個元祖。
所以修改傳遞參數如下:
>>> args = {'a':1,'b':2,'c':3}
>>> args['d'] = 4
>>> f(**args)
1 2 3 4
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
【錯誤分析】在函數hider()內使用了內置變量open,但根據Python作用域規則LEGB的優先級:
先是查找本地變量==》模塊內的其他函數==》全局變量==》內置變量,查到了即停止查找。
所以open在這里只是個字符串,不能作為打開文件來使用,所以報錯,更改變量名即可。
可以導入__builtin__模塊看到所有內置變量:異常錯誤、和內置方法
>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError',..
.........................................zip,filter,map]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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]: int
In [109]: T1 = (1,)
In [110]: T2 = (2,3)
In [111]: T1 + T2
Out[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 = 78
SyntaxError: invalid syntax
【錯誤分析】class是Python保留字,Python保留字不能做變量名,可以用Class,或klass
同樣,保留字不能作為模塊名來導入,比如說,有個and.py,但不能將其作為模塊導入
>>> import and
SyntaxError: 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.__secretCount
count1 = JustCounter()
count1.count()
count1.count()
count1.__secretCount
報錯如下:
>>>
secretCount is: 1
secretCount is: 2
Traceback (most recent call last):
File "D:\Learn\Python\Learn.py", line 13, in <module>
count1.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
【錯誤分析】雙下划線的類屬性__secretCount不可訪問,所以會報無此屬性的錯誤.
解決辦法如下:
# 1. 可以通過其內部成員方法訪問
# 2. 也可以通過訪問
ClassName._ClassName__Attr
#或
ClassInstance._ClassName__Attr
#來訪問,比如:
print count1._JustCounter__secretCount
print JustCounter._JustCounter__secretCount
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> print x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = 1
>>> print x
1
【錯誤分析】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的異常.
next()方法屬於Python的魔法方法,這種方法的效果就是:逐行讀取文本文件的最佳方式就是根本不要去讀取。
取而代之的用for循環去遍歷文件,自動調用next()去調用每一行,且不會報錯
for line in open('test.txt','r'):
print line
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> string = 'SPAM'
>>> a,b,c = string
Traceback (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
^
dentationError: unexpected indent
【錯誤分析】一般是代碼縮進問題,TAB鍵或空格鍵不一致導致
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>>def A():
return A()
>>>A() #無限循環,等消耗掉所有內存資源后,報最大遞歸深度的錯誤
File "<pyshell#2>", line 2, in A return A()RuntimeError: maximum recursion depth exceeded
class 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()
squawk
SingBird是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__=type
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
>>> 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] = 22
TypeError: 'tuple' object does not support item assignment
【錯誤分析】元祖不可變,所以不可以更改;可以用切片或合並的方式達到目的.
>>> T = (1,2,3,4)
>>> (22,) + T[1:]
(22, 2, 3, 4)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>> X = 1;
>>> Y = 2;
>>> X + = Y
File "<stdin>", line 1
X + = Y
^
SyntaxError: invalid syntax
【錯誤分析】增強行賦值不能分開來寫,必須連着寫比如說 +=, *=
>>> X += Y
>>> X;Y
3
2