def func():
something
d = { 'func': func }
d['func']() # callable
d2 = { 'type': { 'func': func } }
d2['type']['func']() # not callable
d3 = { 'type': { 'func': func() } }
d3['type']['func']() # callable
d 和 d2 有什么区别?
为什么 d3 是可调用的而 d2 是不可调用的?
此代码是可执行的,但 pycham 突出显示 d2'func' 并说'dict object is not callable
最佳答案
在 python 中定义一个函数将使其可调用。它在完成时所做的事情只有在您实际调用它时才有意义(通过使用 ()-operator)。如果没有 return 语句的定义,该函数将返回 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
关于python在多维字典中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40925217/