2016-10-22 67 views
0

我沒有顯示整個類的問題是很難做出簡單的,但下面是關鍵,我相信:我創建新引用同一個對象,而不是新的對象

class helper: 
    sharex = False 
    sharey = False 

    _objects = [] 

    _figures = [] 
    _axes = [] 


    def __init__(self): 
     pass 

    def create(self): 
     figure, axes = plt.subplots(nrows=self.nrows, 
           ncols=self.ncols, 
           sharex=self.sharex, 
           sharey=self.sharey) 
     self._figures.append(figure) 
     self._axes.append(axes) 

的以下說明應該我的問題:

test = plotting.helper() 
test._axes 
Out[9]: [] 
test.create() 
test._axes 
Out[10]: 
[array([<matplotlib.axes._subplots.AxesSubplot object at 0x103dd1940>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x10c4a5278>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x10c1889b0>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x11c52eeb8>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x11c56f4a8>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x11c5b7be0>], dtype=object)] 
test2 = plotting.helper() 
test2._axes 
Out[11]: 
[array([<matplotlib.axes._subplots.AxesSubplot object at 0x103dd1940>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x10c4a5278>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x10c1889b0>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x11c52eeb8>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x11c56f4a8>, 
     <matplotlib.axes._subplots.AxesSubplot object at 0x11c5b7be0>], dtype=object)] 

第二個目的應創建空,並且沒有存儲在_axes任何軸。然而,它不僅包含座標軸,而且與(假定)獨立的其他對象一樣,也是相同的。

爲什麼我不創建獨立的對象?

+0

我會建議你閱讀一篇Python OOP教程,它將解釋大部分內容。 – jonrsharpe

回答

0

當您在類聲明中聲明_axes時,將其設爲靜態變量,意味着它與所有實例都是相互關聯的。 您想要將_axes的聲明移至__init__函數。

+0

這個問題已經被標記爲一個騙局。 –

+0

是的,我現在看到它...沒有通知我在移動應用程序。 – Sawel

相關問題