0

I'm not showing the whole class as the problem is difficult to make simple, but the following is key I believe:

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)

The following should illustrate my problem:

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)]

The second object should be created empty, and without any axes stored in _axes. Yet, not only does it contain axes, it's the same axes as the (supposedly) independent other object.

Why am I not creating independent objects?

FooBar
  • 15,724
  • 19
  • 82
  • 171

1 Answers1

0

When you declare _axes in the class declaration, you make it a static variable, means it is mutual to all instances. You want to move the declaration of _axes to the __init__ function.

Sawel
  • 929
  • 7
  • 17