一个函数可以有多个名称吗?

Ser*_*kov 2 python function

我正在使用Python开发一个机器人(2.7,3.4).我定义了大约30多个基于bot命令使用的动态函数.在开发时,由于并非所有函数都已完成,我必须为它们定义一个空函数(如果我没有定义那么代码将不会运行),如下所示:

def c_about():
    return
def c_events():
    return
def c_currentlocation():
    return
Run Code Online (Sandbox Code Playgroud)

许多虚拟功能.

问题:
在Python中以某种方式可以定义相同的函数但具有多个名称?
像这样的东西:

def c_about(), c_events(), c_currentlocation():
    return
Run Code Online (Sandbox Code Playgroud)

Ano*_*ous 5

是的,完全可能,因为定义的函数存储在其他所有变量中.

def foo():
    pass

baz = bar = foo
Run Code Online (Sandbox Code Playgroud)

仍然有一些与原始功能相关的元数据(help(bar)仍将提及foo),但它不会影响功能.

另一种选择是将lambdas用于单行:

foo = bar = baz = lambda: None
Run Code Online (Sandbox Code Playgroud)


daw*_*awg 5

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

>>> 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'
Run Code Online (Sandbox Code Playgroud)

很明显你可以这样做:

>>> c=d=e=f=g=a
>>> e
<function a at 0x101c892a8>
Run Code Online (Sandbox Code Playgroud)

对于尚未定义的函数,您可以try/catch通过捕获 a来使用块NameError

def default():
    print "default called"

try:
    not_defined()
except NameError:
    default()
Run Code Online (Sandbox Code Playgroud)

或者使用 funcs 的 dict 并捕获KeyError

funcs={"default": default}

try:
    funcs['not_defined']()
except KeyError:
    funcs['default']()      
Run Code Online (Sandbox Code Playgroud)

或者,funcs.get(not_defined, default)()如果您更喜欢带有 funcs dict 的语法,则可以这样做。