首页 > 解决方案 > 在 Python 中更改函数名称

问题描述

考虑这个例子:

def foo():
    raise BaseException()

globals()["bar"] = foo
foo.__name__ = "bar"
# foo.__code__.co_name = "bar" # - Error: property is readonly

bar()

输出是:

Traceback (most recent call last):
  File "*path*/kar.py", line 9, in <module>
    bar()
  File "*path*/kar.py", line 2, in foo
    raise BaseException()
BaseException

如何在回溯中更改函数名称“foo”?我已经尝试过foo.__name__ = "bar",globals()["bar"] = foofoo.__code__.co_name = "bar",但是前两个什么都不做,第三个失败了AttributeError: readonly attribute

标签: python

解决方案


更新:更改函数回溯名称

您想在您调用的函数中返回一个具有不同名称的函数。

def foo():
    def bar():
        raise BaseException
    return bar

bar = foo()

bar()

观察以下回溯: 在此处输入图像描述

旧答案:所以我假设您的目标是能够使用 bar() 将 foo 称为 bar。

我认为您需要做的是将变量名称设置为等于您要调用的函数。如果您在函数定义上方和函数外部定义变量,则该变量是全局变量(可以在后续函数定义中使用)。

请参阅以下代码和屏幕截图。

def foo():
    for i in range(1,11):
        print(i)


bar = foo #Store the function in a variable name = be sure not to put parentheses - that tells it to call!

bar() #call the function you stored in a variable name
print(bar) #print the function's location in memory to show that it is stored.

让我知道您是否尝试做一些不同的事情,或者您只是想将函数存储在稍后调用的变量中。 在此处输入图像描述


推荐阅读