python在多维字典中使用函数

标签 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

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/

相关文章:

python - 通过嵌套字典键获取唯一列表项

python - 当我尝试运行 table.scan() 时,为什么 happybase 返回 "TSocket read 0 bytes"?

Python 与 MySql "SAWarning: Unicode type received non-unicode bind param value"错误

c# - 将嵌套的 JSON 反序列化为字典、字符串和类

python - 迭代地组合列表并检查Python中的下一个列表

python - 更改 __hash__ 的类仍然适用于字典访问

python - PyCharm 警告 : Unexpected type for filter on dictionary

python - 错误 'long' 对象没有属性 'fetchall'

python - 在 Python 中使用变量与 PostgreSQL 通信

java - 通过 hashmap 的键值逐个字母迭代字符串以获得总和