A private list variable is inadvertently shared between instance objects

前端 未结 2 468
执笔经年
执笔经年 2021-01-26 02:11

I created many instances of a PlotHandler class. An instance must keep it\'s variables private. But the way I managed them led to a hard to detect problem,

相关标签:
2条回答
  • 2021-01-26 02:26

    Class attributes are shared between instances. If you want to define an instance attribute (so each object have its own reference to the variable) you have to define it in __init__

    class PlotHandler(wx.Frame):
        __crop_section = None
        __projection   = None
        __crop_xcord   = None
    
        def __init__(self, **kwargs):
            self._band_data = [] #THIS IS NOT SHARED
    
    0 讨论(0)
  • 2021-01-26 02:48

    See this question, this one, and tons of other stuff you can find by googling "Python class variables shared", "Python FAQ class variables", etc.

    The short answer is: variables defined directly in the class body are class variables, not instance variables, and are thus shared among instances of the class. If you want instance variables you must assign them from within a method, where you have access to self.

    0 讨论(0)
提交回复
热议问题