在Python中更改函数名

2024-09-27 09:33:06 发布

您现在位置: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",但是前两个什么都不做,第三个失败了。你知道吗


Tags: pathnameinpyfoolinebarcode
1条回答
网友
1楼 · 发布于 2024-09-27 09:33:06

更新:更改函数回溯名称

您希望在所调用的函数中返回具有不同名称的函数。你知道吗

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

bar = foo()

bar()

观察以下回溯: enter image description here

旧答案: 所以我假设您的目标是能够使用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.

如果你想做些不同的事情,或者你只是想把一个函数存储在一个变量中以便以后调用,请告诉我。 enter image description here

相关问题 更多 >

    热门问题