不,函數的行爲不會根據是否存儲對返回值的引用進行更改,或者完全忽略它。在返回值被存儲或忽略之前,該函數被執行。如果函數調用導致引發異常,則根本不會有返回值。
您對發生的事情的分析不正確,問題在於別處。
你可以很容易地這個自己雖然測試:
>>> def foo():
... print "foo() called"
...
>>> def bar():
... return foo()
...
>>> bar()
foo() called
>>> result = bar()
foo() called
,或者使用urllib2.urlopen()
本身,使用http://httpbin.org/status/404
觸發404未找到響應:
>>> import urllib2
>>> response = urllib2.urlopen('http://httpbin.org/status/404')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: NOT FOUND
>>> urllib2.urlopen('http://httpbin.org/status/404')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: NOT FOUND
兩項行動引發異常。
作爲返回值的分配情況發生*之後*被執行的功能,這是不可能的功能,以瞭解其是否返回價值被賦予某種東西。正如Martijn所說,你的錯誤在別處。 – poke
@MartijnPieters這不完全正確,有許多使用yield的函數,除非你用它做什麼,否則不會做任何有意義的事情。 – Soviero
@Soviero:那些是發電機功能。他們**做**返回東西,一個發電機對象。但是urlopen()不是生成器函數。 –