python use function in multi dimension dictionary

时间:2016-12-02 05:10:56

标签: python dictionary

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

What is different between d and d2 ?

Why d3 is callable and d2 is not callable ?

this code is executable but pycham highlight d2'func' and say 'dict object is not callable

1 个答案:

答案 0 :(得分:0)

在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