Skip to main content
 首页 » 编程设计

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

2025年05月04日10kuangbin

我在一个类中有两个函数,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