2017-02-23 36 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