python定义多维字典_python在多维字典中使用函数

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值