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对象不可调用
解决方法:
在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 "", line 1, in
File "", line 2, in func
NameError: global name 'something' is not defined
>>>
>>> d2 = { 'type': { 'func': func } }
>>> d2['type']['func']()
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in func
NameError: global name 'something' is not defined
>>>
>>> d3 = { 'type': { 'func': func() } }
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in func
NameError: global name 'something' is not defined
>>> d3['type']['func']()
Traceback (most recent call last):
File "", line 1, in
NameError: name 'd3' is not defined
标签:python,dictionary
来源: https://codeday.me/bug/20190710/1429128.html