Python常見的錯誤匯總


Python常見的錯誤匯總

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

錯誤:

TypeError: 'NoneType' object is not callable

【錯誤分析】我是在別的文件中寫了一個函數,然后在python console調用使用該函數,出現了上述錯誤。原因是因為沒有對別的文件中函數進行編譯,只要打開該調用函數的文件,然后點擊運行,之后再在python console中調用使用該函數就不會報錯。

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

錯誤:

【錯誤分析】第二個參數必須為類,否則會報TypeError,所以正確的應該是這樣的:

但如果第二個參數是類型對象,則不會報上面的錯誤,是允許的,比如說:

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

錯誤:

【錯誤分析】這個涉及到調用順序問題,即解析方法的MRO調用順序,在Python2.7版本之后,這樣調用會報錯,

必須是子類先放前面,然后才是父類.如下所示,方不會報錯.

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

錯誤:

【錯誤分析】foo()未帶參數self,也未帶cls參數,屬於類的靜態方法,類的靜態方法調用,實例不能直接調用,需要再聲明一個靜態方法

或者通過@staticmethod來調用

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

錯誤:

【錯誤分析】__dict__是實例的特殊屬性,但在內建屬性中,不存在__dict__屬性,一般的情況是:

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

錯誤:

【錯誤分析】如果定義了構造器,它不應當返回任何對象,因為實例對象是自動在實例化調用后返回的。相應地,__init__()就不應當返回任何對象(應當為None);否則就可能出現沖突,因為只能返回實例。試着返回非None的任何其他對象都會導致TypeError異常

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

錯誤:

 

1 >>> def f(x, y):  
2     print x, y  
3 >>> t = ('a', 'b')  
4 >>> f(t)  
5   
6 Traceback (most recent call last):  
7   File "<pyshell#65>", line 1, in <module>  
8     f(t)  
9 TypeError: f() takes exactly 2 arguments (1 given)

 

 

 

【錯誤分析】不要誤以為元組里有兩個參數,將元組傳進去就可以了,實際上元祖作為一個整體只是一個參數,

實際需要兩個參數,所以報錯。必需再傳一個參數方可.

1 >>> f(t, 'var2')  
2 ('a', 'b') var2  

更常用的用法: 在前面加*,代表引用元組 

1 >>> f(*t)  
2 'a', 'b'  

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

錯誤:

 

1 >>> def func(y=2, x):  
2     return x + y  
3 SyntaxError: non-default argument follows default argument 

 

 

 

【錯誤分析】在C++,Python中默認參數從左往右防止,而不是相反。這可能跟參數進棧順序有關。

1 >>> def func(x, y=2):  
2     return x + y  
3 >>> func(1)  
4 3 

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

錯誤:

 

1 >>> D1 = {'x':1, 'y':2}  
2 >>> D1['x']  
3 1  
4 >>> D1['z']  
5   
6 Traceback (most recent call last):  
7   File "<pyshell#185>", line 1, in <module>  
8     D1['z']  
9 KeyError: 'z' 

 

【錯誤分析】這是Python中字典鍵錯誤的提示,如果想讓程序繼續運行,可以用字典中的get方法,如果鍵存在,則獲取該鍵對應的值,不存在的,返回None,也可打印提示信息.

1 >>> D1.get('z', 'Key Not Exist!')  
2 'Key Not Exist!' 
 
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

錯誤:

1 >>> from math import sqrt  
2 >>> exec "sqrt = 1"  
3 >>> sqrt(4)  
4   
5 Traceback (most recent call last):  
6   File "<pyshell#22>", line 1, in <module>  
7     sqrt(4)  
8 TypeError: 'int' object is not callable  
【錯誤分析】exec語句最有用的地方在於動態地創建代碼字符串,但里面存在的潛在的風險,它會執行其他地方的字符串,在CGI中更是如此!比如例子中的sqrt = 1,從而改變了當前的命名空間,從math模塊中導入的sqrt不再和函數名綁定而是成為了一個整數。要避免這種情況,可以通過增加in <scope>,其中<scope>就是起到放置代碼字符串命名空間的字典。
1 >>> from math import sqrt  
2 >>> scope = {}  
3 >>> exec "sqrt = 1" in scope  
4 >>> sqrt(4)  
5 2.0 

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

錯誤:

1 >>> seq = [1, 2, 3, 4]  
2 >>> sep = '+'  
3 >>> sep.join(seq)  
4   
5 Traceback (most recent call last):  
6   File "<pyshell#25>", line 1, in <module>  
7     sep.join(seq)  
8 TypeError: sequence item 0: expected string, int found  

【錯誤分析】join是split的逆方法,是非常重要的字符串方法,但不能用來連接整數型列表,所以需要改成:

1 >>> seq = ['1', '2', '3', '4']  
2 >>> sep = '+'  
3 >>> sep.join(seq)  
4 '1+2+3+4' 

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

錯誤:

 

1 >>> print r'C:\Program Files\foo\bar\'  
2 SyntaxError: EOL while scanning string literal  

 

【錯誤分析】Python中原始字符串以r開頭,里面可以放置任意原始字符,包括\,包含在字符中的\不做轉義。

但是,不能放在末尾!也就是說,最后一個字符不能是\,如果真 需要的話,可以這樣寫:

1 >>> print r'C:\Program Files\foo\bar' "\\"  
2 C:\Program Files\foo\bar\  
3 >>> print r'C:\Program Files\foo\bar' + "\\"  
4 C:\Program Files\foo\bar\   

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

代碼:

1 bad = 'bad'  
2   
3 try:  
4     raise bad  
5 except bad:  
6     print 'Got Bad!' 

錯誤:

1 >>>   
2   
3 Traceback (most recent call last):  
4   File "D:\Learn\Python\Learn.py", line 4, in <module>  
5     raise bad  
6 TypeError: exceptions must be old-style classes or derived from BaseException, not str 

【錯誤分析】因所用的Python版本2.7,比較高的版本,raise觸發的異常,只能是自定義類異常,而不能是字符串。所以會報錯,字符串改為自定義類,就可以了。

 1 class Bad(Exception):  
 2     pass  
 3   
 4 def raiseException():  
 5     raise Bad()  
 6   
 7 try:  
 8     raiseException()  
 9 except Bad:  
10     print 'Got Bad!' 

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

 錯誤:

 1 class Super:  
 2     def method(self):  
 3         print "Super's method"  
 4   
 5 class Sub(Super):  
 6     def method(self):  
 7         print "Sub's method"  
 8         Super.method()  
 9         print "Over..."  
10   
11 S = Sub()  
12 S.method() 

執行上面一段代碼,錯誤如下:

1 >>>   
2 Sub's method  
3   
4 Traceback (most recent call last):  
5   File "D:\Learn\Python\test.py", line 12, in <module>  
6     S.method()  
7   File "D:\Learn\Python\test.py", line 8, in method  
8     Super.method()  
9 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參數即可。

 1 class Super:  
 2     def method(self):  
 3         print "Super's method"  
 4   
 5 class Sub(Super):  
 6     def method(self):  
 7         print "Sub's method"  
 8         Super.method(self)  
 9         print "Over..."  
10   
11 S = Sub()  
12 S.method()  
13   
14   
15 #輸出結果  
16 >>>   
17 Sub's method  
18 Super's method  
19 Over... 

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

錯誤:
1 >>> reload(sys)  
2 Traceback (most recent call last):  
3   File "<stdin>", line 1, in <module>  
4 NameError: name 'sys' is not defined  

【錯誤分析】reload期望得到的是對象,所以該模塊必須成功導入。在沒導入模塊前,不能重載.

1 >>> import sys  
2 >>> reload(sys)  
3 <module 'sys' (built-in)>  

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

 錯誤 

 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 1, in <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 1, in <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__模塊看到所有內置變量:異常錯誤、和內置方法

1  import __builtin__
2 >>> dir(__builtin__)
3 ['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]: (1, 2, 3) 

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

 錯誤:

1 >>> hash(1,(2,[3,4]))  
2   
3 Traceback (most recent call last):  
4   File "<pyshell#95>", line 1, in <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 {(3, 4): 5}  

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

錯誤:

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

【錯誤分析】列表屬於可變對象,其append(),sort(),reverse()會在原處修改對象,不會有返回值,

或者說返回值為空,所以要實現反轉並排序,不能並行操作,要分開來寫

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

或者用下面的方法實現:

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

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

 錯誤:

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 1, in <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(2) for y in range(3)]  
2   File "<stdin>", line 1  
3     [x,y for x in range(2) for y in range(3)]  
4            ^  
5 SyntaxError: invalid syntax  

【錯誤分析】錯誤原因,列表解析中,x,y必須以數組的方式列出(x,y)

1 >>> [(x,y) for x in range(2) for y in range(3)]  
2 [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]  

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

 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 is: 1  
3 secretCount is: 2  
4   
5   
6 Traceback (most recent call last):  
7   File "D:\Learn\Python\Learn.py", line 13, in <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 >>> t = (1,2)  
 2 >>> t.append(3)  
 3 Traceback (most recent call last):  
 4   File "<stdin>", line 1, in <module>  
 5 AttributeError: 'tuple' object has no attribute 'append'  
 6 >>> t.remove(2)  
 7 Traceback (most recent call last):  
 8   File "<stdin>", line 1, in <module>  
 9 AttributeError: 'tuple' object has no attribute 'remove'  
10 >>> t.pop()  
11 Traceback (most recent call last):  
12   File "<stdin>", line 1, in <module>  
13 AttributeError: 'tuple' object has no attribute 'pop'  

【錯誤分析】屬性錯誤,歸根到底在於元組是不可變類型,所以沒有這幾種方法.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 1 >>> t = ()  
 2 >>> t[0]  
 3 Traceback (most recent call last):  
 4   File "<stdin>", line 1, in <module>  
 5 IndexError: tuple index out of range  
 6 >>> l = []  
 7 >>> l[0]  
 8 Traceback (most recent call last):  
 9   File "<stdin>", line 1, in <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 1, in <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 1, in <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 1, in ?  
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 2, in 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 1, in <module>  
35     s.eat()  
36   File "D:\Learn\Python\Person.py", line 42, in 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 1, in <module>  
20     sb = SingBird()  
21   File "D:\Learn\Python\Person.py", line 51, in __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 (1, 2, 3, 4)  
3 >>> T[0] = 22   
4 Traceback (most recent call last):  
5   File "<pyshell#129>", line 1, in <module>  
6     T[0] = 22  
7 TypeError: 'tuple' object does not support item assignment  

 

 

1 >>> T  
2 (1, 2, 3, 4)  
3 >>> T[0] = 22   
4 Traceback (most recent call last):  
5   File "<pyshell#129>", line 1, in <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 (22, 2, 3, 4)  

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

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

 參考:http://blog.csdn.net/jerry_1126/article/details/39395899


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM