gpt4 book ai didi

python - 复制签名,转发包装函数的所有参数

转载 作者:太空宇宙 更新时间:2023-11-04 06:59:56 25 4
gpt4 key购买 nike

我在一个类中有两个函数,plot()show()show(),作为一种方便的方法,除了在 plot() 的代码中添加两行之外什么都不做,比如

def plot(
self,
show_this=True,
show_that=True,
color='k',
boundary_color=None,
other_color=[0.8, 0.8, 0.8],
show_axes=True
):
# lots of code
return

def show(
self,
show_this=True,
show_that=True,
color='k',
boundary_color=None,
other_color=[0.8, 0.8, 0.8],
show_axes=True
):
from matplotlib import pyplot as plt
self.plot(
show_this=show_this,
show_that=show_that,
color=color,
boundary_color=boundary_color,
other_color=other_color,
show_axes=show_axes
)
plt.show()
return

一切正常。

我遇到的问题是,方式 show() 包装器中的代码似乎太多了。我真正想要的是:让 show() 具有与 plot() 相同的签名和默认参数,并将所有参数转发给它。

有什么提示吗?

最佳答案

Python 3 提供了使用 inspect 模块实际复制包装函数签名的能力:

def show(self, *args, **kwargs):
from matplotlib import pyplot as plt
self.plot(*args, **kwargs)
plt.show()
show.__signature__ = inspect.signature(plot)

现在,如果您在像 IDLE 这样提供自动完成功能的 shell 中使用 show,您将看到 show 的正确参数,而不是密码 *args, **kwargs

关于python - 复制签名,转发包装函数的所有参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com