一个函数可以有多个名字? [英] Can one function have multiple names?

查看:102
本文介绍了一个函数可以有多个名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Python的机器人(2.7,3.4)。我定义了大约30多个基于bot命令的动态函数。在开发过程中,由于并不是所有的功能都完成了,我必须为它们定义一个空函数(如果我没有定义,代码将不会运行),如下所示:

<$ p $ ():
返回
def c_about():
返回
def c_events():
返回
def c_currentlocation():
返回

等。很多虚拟函数。



问题:
在Python中以某种方式可能定义相同的函数,但




$ c $ def c_about(),c_events() ,c_currentlocation():
return


解决方案

函数不要实习(即自动共享多个引用到同一个不可变的对象),但可以共享同名:

 >>> def a():传递
...
>>> a
<函数a在0x101c892a8>
>>> def b():通过
...
>>> b
<函数b在0x101c89320>
>>> c = a
>>> c
<函数a在0x101c892a8> #注意物理地址与'a'相同

很明显你可以这样做:

 >>> c = d = e = f = g = a 
>>> e
<函数a在0x101c892a8>

对于尚未定义函数的情况,可以使用 try /通过捕获 NameError

 <$ c $捕获 c)def default():
printdefault called

try:
not_defined()
除了NameError:
default()

或者使用func的字典并捕获 KeyError

  funcs = {default:default} 

尝试:
funcs ['' not_defined']()
除KeyError:
funcs ['default']()

或者,如果您喜欢那种带有funcs字典的语法,您可以执行 funcs.get(not_defined,default)()

I'm developing a bot on Python (2.7, 3.4). I defined a about 30+ dynamic functions which to be used based on bot commands. While development, since not all functions are done, I have to define for them an empty functions (if I not define then code won't run) like this:

def c_about():
    return
def c_events():
    return
def c_currentlocation():
    return

etc. many dummy functions.

Question:
it is somehow possible in Python to define same function but with multiple names?
Something like this:

def c_about(), c_events(), c_currentlocation():
    return

解决方案

Functions do not intern (i.e., automatically share multiple references to the same immutable object), but can share the same name:

>>> def a(): pass
... 
>>> a
<function a at 0x101c892a8>
>>> def b(): pass
... 
>>> b
<function b at 0x101c89320>
>>> c=a
>>> c
<function a at 0x101c892a8>  # note the physical address is the same as 'a'

So clearly you can do:

>>> c=d=e=f=g=a
>>> e
<function a at 0x101c892a8>

For the case of functions not yet defined, you can use a try/catch block by catching either a NameError:

def default():
    print "default called"

try:
    not_defined()
except NameError:
    default()

Or use a dict of funcs and catch the KeyError:

funcs={"default": default}

try:
    funcs['not_defined']()
except KeyError:
    funcs['default']()      

Or, you can do funcs.get(not_defined, default)() if you prefer that syntax with a dict of funcs.

这篇关于一个函数可以有多个名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆