2017-02-23 37 views
0

我在一个类中有两个函数,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()相同的签名和默认参数,并将所有参数转发给它。

任何提示?如果你

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

现在:

+0

'i nspect'模块自Python 3.3以来有一个'Signature'类。 –

+0

Python 2或Python 3?后者有更多的可能性来复制签名 –

+0

代码必须与Python 2兼容,但我会对你提到的可能性感到好奇。 –

回答

2

您可以使用参数压缩/解压缩的:

def show(self, *args, **kwargs): 
    from matplotlib import pyplot as plt 
    self.plot(*args, **kwargs) 
    plt.show() 
1

的Python 3提供了实际的签名与检查模块复制包装的函数的能力使用显示提供像IDLE自动完成的外壳,您将看到show而不是密码的正确参数*args, **kwargs