一个函数可以有多个名字? [英] Can one function have multiple names?
问题描述
我正在开发一个Python的机器人(2.7,3.4)。我定义了大约30多个基于bot命令的动态函数。在开发过程中,由于并不是所有的功能都完成了,我必须为它们定义一个空函数(如果我没有定义,代码将不会运行),如下所示:
<$ p $ ():
返回
def c_about():
返回
def c_events():
返回
def c_currentlocation():
返回
等。很多虚拟函数。
问题: 函数不要实习(即自动共享多个引用到同一个不可变的对象),但可以共享同名: 很明显你可以这样做: 对于尚未定义函数的情况,可以使用 或者使用func的字典并捕获 或者,如果您喜欢那种带有funcs字典的语法,您可以执行 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: etc. many dummy functions. Question:
Functions do not intern (i.e., automatically share multiple references to the same immutable object), but can share the same name: So clearly you can do: For the case of functions not yet defined, you can use a Or use a dict of funcs and catch the Or, you can do 这篇关于一个函数可以有多个名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
在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()
KeyError
:
funcs = {default:default}
尝试:
funcs ['' not_defined']()
除KeyError:
funcs ['default']()
funcs.get(not_defined,default)()
。 def c_about():
return
def c_events():
return
def c_currentlocation():
return
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
>>> 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'
>>> c=d=e=f=g=a
>>> e
<function a at 0x101c892a8>
try/catch
block by catching either a NameError
:def default():
print "default called"
try:
not_defined()
except NameError:
default()
KeyError
:funcs={"default": default}
try:
funcs['not_defined']()
except KeyError:
funcs['default']()
funcs.get(not_defined, default)()
if you prefer that syntax with a dict of funcs.