其實標題並不完全反映我想問的問題。我的目的是這樣的:我正在使用matplotlib編寫一些繪圖函數。我有一系列用於不同繪圖目的的功能。像line_plot()爲線,bar_plot()爲杆等,例如:使用python裝飾器自動替換函數參數的默認值?
import matplotlib.pyplot as plt
def line_plot(axes=None,x=None,y=None):
if axes==None:
fig=plt.figure()
axes=fig.add_subplot(111)
else:
pass
axes.plot(x,y)
def bar_plot(axes=None,x=None,y=None):
if axes==None:
fig=plt.figure()
axes=fig.add_subplot(111)
else:
pass
axes.bar(left=x,height=y)
然而問題是,對於已定義的每個功能,我必須重複這部分代碼:
if axes==None:
fig=plt.figure()
axes=fig.add_subplot(111)
else:
pass
有沒有像使用裝飾器的方式,我可以在繪圖函數的定義之前應用它,它會自動執行代碼的重複部分?因此我不必每次重複。
一個可能的選擇是這樣定義一個函數:
def check_axes(axes):
if axes==None:
fig=plt.figure()
axes=fig.add_subplot(111)
return axes
else:
return axes
然後例子如:
import matplotlib.pyplot as plt
def line_plot(axes=None,x=None,y=None):
axes=check_axes(axes)
axes.plot(x,y)
def bar_plot(axes=None,x=None,y=None):
axes=check_axes(axes)
axes.bar(left=x,height=y)
但有沒有更好/清潔/更Python的方式?我想我可以使用裝飾器,但沒有弄清楚。有人可以提出一些想法嗎?
謝謝!
我認爲你最後的解決方案非常好。函數是有效的,經過驗證的構造代碼的方法。我懷疑裝飾者會不必要地使事情複雜化。 – 2012-08-02 08:43:58
也許你可以在你的測試中創建一個軸類,它的init – zenpoy 2012-08-02 09:22:42