python - 在 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"] = foo
和foo.__code__.co_name = "bar"
,但是前两个什么都不做,第三个失败了AttributeError: readonly attribute
。
解决方案
更新:更改函数回溯名称
您想在您调用的函数中返回一个具有不同名称的函数。
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.
推荐阅读
- c - FFTW大师界面
- java - assertThat 逐个字段或比较对象
- angular - product.images.GALLERY.map 不是函数 | 斯巴达克斯电信 PDP
- dataframe - 矩阵乘法与 DataFrames (Julia)
- google-apps-script - 如何对包含 Google 表格中的函数的范围进行排序
- java - 如何修复页面右侧表格列中的失真,我有一些问题,无法展开导航栏和表格
- c# - 我如何发帖
- azure - Azure Artifacts 使用 vsts-npm-auth 更新凭据
- tomcat - 未找到 OpenGrok 和 Tomcat 404
- css - 更改方向时iOS上的动画填充模式问题