函数中的Python Try-Except [英] Python Try-Except inside of Function
问题描述
我对python的try-except子句有很好的理解,但是当尝试将其放在函数中时,我遇到问题。
I've got a pretty good understanding of python's try-except clause, but I'm encountering problems when trying to put it inside of a function.
>>> def tryAppend(child, parent):
... try:
... parent.append(child)
... except NameError:
... print "WRONG NAME"
>>> var1 = []
>>> var2 = 'test2'
>>> tryAppend(var2, var1) #works, no error
>>> tryAppend(foo, var1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
几乎就像python不看到try:语句。任何帮助都不胜感激。
it is almost like python doesn't see the try: statement. Any help is appreciated.
推荐答案
我对python的尝试非常了解条款
I've got a pretty good understanding of python's try-except clause
否。那么,也许你有,但是你在其他更重要的领域严重缺乏。或者你期望尝试(双关不是意图)范围神奇地扩大,或者你不明白什么顺序代码被评估...我会假设后者。 tryAppend(foo,var1)
按此顺序进行评估(粗略地):
No. Well, maybe you have, but then you severely lack in other, much more important areas. Either you expect try's (pun not intended) scope magically expand, or you don't understand in what order code is evaluated... I will assume the latter. tryAppend(foo, var1)
is evaluated (roughly) in this order:
- 获取对象
tryAppend
引用 - 获取对象
foo
references - 获取对象
var1
references - 调用第二个和第三个参数(= do无论
tryAppend
的功能如何,不包括try-except)
- Fetch the object
tryAppend
references - Fetch the object
foo
references - Fetch the object
var1
references - Call the first with the second and third as arguments (=do whatever the function
tryAppend
does, uncluding the try-except)
错误在功能和try块输入前很久就发生在#2。实际上,try块不能抛出一个NameError,因为唯一使用的名称是 parent
和 child
,都是参数,因此始终可用(如果 .append
不存在,那就是一个 AttributeError
)
The error occurs at #2, long before the function and the try block is entered. In fact, the try block cannot to throw a NameError, as the only names used are parent
and child
, both being arguments and thus always available (if .append
does not exist, that's an AttributeError
).
你问为什么
raise Exception("Catch me if you can")
try:
pass # do nothing
except:
print "caught it"
不打印抓住它。
这篇关于函数中的Python Try-Except的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!