⾃⼰编程中遇到的Python错误和解决⽅法汇总整理
开个贴,⽤于记录平时经常碰到的Python的错误同时对导致错误的原因进⾏分析,并持续更新,⽅便以后查询,学习。知识在于积累嘛!微笑php正则预查>nodejs配置文件在哪
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
错误:
复制代码代码如下:
>>> 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)
精通css第三版pdf'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
python基础代码实例>>> 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"
print ""
S = Sub()
执⾏上⾯⼀段代码,错误如下:
复制代码代码如下:
>>>
Sub's method
Traceback (most recent call last):颜html代码大全
File "D:\Learn\Python\test.py", line 12, in <module>
File "D:\Learn\Python\test.py", line 8, in method
TypeError: unbound method method() must be called with Super instance as first argument (got nothing instead)  【错误分析】Python中调⽤类的⽅法,必须与实例绑定,或者调⽤⾃⾝.
复制代码代码如下:
所以上⾯代码,要调⽤Super类的话,只需要加个self参数即可。
复制代码代码如下:
class Super:
def method(self):
print "Super's method"
class Sub(Super):
def method(self):
print "Sub's method"
print ""
S = Sub()
#输出结果
>>>
Sub's method
Super's method
shell脚本怎么输入参数<
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
复制代码代码如下:
>>> 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]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
复制代码代码如下:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。