在Python中定義功能將使它調用。它在完成時的作用只有在你實際調用它時纔有意義(通過使用()-operator)。沒有定義返回語句,函數將返回None。如此處所述:Python -- return, return None, and no return at all。
當執行提供的命令,它試圖調用函數func,因爲一些沒有被定義爲快進肚了。我擔心pycharm正在做一些無效的突出顯示。 d和d2是可調用的,但是d3不是。由於您在分配d3時調用了func,因此此處的錯誤和d3不存在。
Python 2.7.12 (default, Oct 10 2016, 12:50:22)
[GCC 5.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
dlopen("/usr/lib/python2.7/lib-dynload/readline.dll", 2);
import readline # dynamically loaded from /usr/lib/python2.7/lib-dynload/readline.dll
>>>
>>> def func():
... something
...
>>> d = { 'func': func }
>>> d['func']()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func
NameError: global name 'something' is not defined
>>>
>>> d2 = { 'type': { 'func': func } }
>>> d2['type']['func']()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func
NameError: global name 'something' is not defined
>>>
>>> d3 = { 'type': { 'func': func() } }
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func
NameError: global name 'something' is not defined
>>> d3['type']['func']()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd3' is not defined
來源
2016-12-25 11:08:29
mic
'd2 ['func']'和'd3 ['func']'都會拋出錯誤。您正在抓取不存在的鍵('func')。你的意思是'd2 ['type'] ['func']'和'd3 ['type'] ['func']'? – Abdou
你最後兩個例子不應該工作。 ''func「'不是'dict()' –
的直接鍵,對不起,我剛剛更新。 –