加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python在多维字典中使用函数

发布时间:2020-12-20 13:15:20 所属栏目:Python 来源:网络整理
导读:def func(): somethingd = { 'func': func }d['func']() # callabled2 = { 'type': { 'func': func } }d2['type']['func']() # not callabled3 = { 'type': { 'func': func() } }d3['type']['func']() # callable d和d2有什么不同? 为什么d3可以调用而d2不
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 "<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>",in func
NameError: global name 'something' is not defined
>>>
>>> d3 = { 'type': { 'func': func() } }
Traceback (most recent call last):
  File "<stdin>",in func
NameError: global name 'something' is not defined
>>> d3['type']['func']()
Traceback (most recent call last):
  File "<stdin>",in <module>
NameError: name 'd3' is not defined

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读