【问题标题】:python use function in multi dimension dictionarypython在多维字典中使用函数
【发布时间】:2017-04-16 22:50:15
【问题描述】:
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

【问题讨论】:

  • d2['func']d3['func'] 都应该抛出错误。您正在抓取不存在的密钥 (func)。你的意思是d2['type']['func']d3['type']['func']
  • 另外,something 到底是什么? something 可以是可调用类型。
  • 函数定义在这里非常重要。所以不能只是do something
  • 如果函数没有返回任何内容(即只是print),d3['type']['func'] 将无法与后面的括号配合使用。没有return 语句的函数将返回None。男孩,你不想喂None 一组括号。因此,请务必返回 function
  • @OhSungCho 如果您可以添加基于 Abdou 的 cmets 的精简版函数并在您的问题中添加更多数据以供参考,那就太好了。

标签: python dictionary


【解决方案1】:

在 python 中定义一个函数将使其可调用。它在完成时所做的只有在您实际调用它时才相关(通过使用 () 运算符)。如果没有定义 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

【讨论】:

    猜你喜欢
    • 2012-11-19
    • 2016-08-05
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多