考虑这个例子:
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"] = foo
和foo.__code__.co_name = "bar"
,但是前两个什么都不做,第三个失败了。你知道吗
更新:更改函数回溯名称
您希望在所调用的函数中返回具有不同名称的函数。你知道吗
观察以下回溯:
旧答案: 所以我假设您的目标是能够使用bar()将foo调用为bar。你知道吗
我认为您需要做的是将变量名设置为要调用的函数。如果在函数定义上方和函数外部定义变量,则该变量是全局变量(可以在后续函数定义中使用)。你知道吗
请参见以下代码和屏幕截图。你知道吗
如果你想做些不同的事情,或者你只是想把一个函数存储在一个变量中以便以后调用,请告诉我。
相关问题 更多 >
编程相关推荐