Python中str is not callable問題詳解及解決辦法
問題提出:
在Python的代碼,在運行過程中,碰到了一個錯誤信息:
python代碼:
1
2
3
4
5
6
7
8
|
def check_province_code(province, country): num = len (province) while num < 3 : province = ''.join([ str ( 0 ),province]) num = num + 1 return country + province |
運行的錯誤信息:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
check_province_code( 'ab' , '001' ) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TypeError Traceback (most recent call last) <ipython - input - 44 - 02ec8a351cce > in <module>() - - - - > 1 check_province_code( 'ab' , '001' ) <ipython - input - 43 - 12db968aa80a > in check_province_code(province, country) 3 4 while num < 3 : - - - - > 5 province = ''.join([ str ( 0 ),province]) 6 num = num + 1 7 TypeError: 'str' object is not callable |
問題分析與排查:
從錯誤信息分析, str不是一個可調用的對象,可是之前確實可以調用的,且在python的api文檔中,其是python內置的一個函數呀, 怎么不能用了呢?
還是繼續驗證一下吧。
在命令行下執行str(123),將數字轉換為string:
1
2
3
4
5
6
7
|
>>> str ( 1233 ) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TypeError Traceback (most recent call last) <ipython - input - 45 - afcef5460e92> in <module>() - - - - > 1 str ( 1233 ) TypeError: 'str' object is not callable |
這下問題定義清楚了,原來沒有了str,仔細想了想原來剛才在定義變量的時候,隨機使用str,所以就被覆蓋了str函數。進行了類似以下的操作:
1
|
str = '123' |
恢復默認的str函數
重新啟動一下python應用,移除str被覆蓋的代碼部分即可。
總結
在python中內置了很多的函數和類,在自己定義變量的時候,切記不要覆蓋或者和他們的名字重復。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/blueheart20/article/details/52883045