Here I’m subclassing a wxPython class and defining a class method called singleton.
class AddressCellAttr(wx.grid.GridCellAttr):
_instance = None
def __init__(self):
wx.grid.GridCellAttr.__init__(self)
self.SetTextColour('#0000FF')
@classmethod
def singleton(cls):
if cls._instance == None:
cls._instance = cls()
return cls._instance
class ValidAddressCellAttr(AddressCellAttr):
def __init__(self):
AddressCellAttr.__init__(self)
self.SetTextColour('#00FF00')
class CorrectedAddressCellAttr(AddressCellAttr):
def __init__(self):
AddressCellAttr.__init__(self)
self.SetTextColour('#FFFF00')
class InvalidAddressCellAttr(AddressCellAttr):
def __init__(self):
AddressCellAttr.__init__(self)
self.SetTextColour('#FF0000')
class UnparsableAddressCellAttr(AddressCellAttr):
def __init__(self):
AddressCellAttr.__init__(self)
self.SetTextColour('#555555')
The rest of the classes are subclasses of the first subclass. I figured that the singleton class method would work for all the subclasses as well since it operates on the class, and the subclass is indeed a separate class.
What happens is that after I call singleton once on AddressCellAttr, the singleton method returns that same object on all the subclasses too. Why does this happen?
Not sure why you think you need a singleton pattern here, but in any case, you should really be doing this in
__new__.Just make sure all subclasses call parent
__new__(), and remember that the signature for__new__()and__init__()must match.