Previous post Reorganize new and init so
class SheetData():
def __init__(self, shtnam, toprow, keyclm, lftclm, rgtclm):
self.data = get_sheet_data(shtnam, toprow, keyclm, lftclm, rgtclm)
self.clmcnt = rgtclm - lftclm + 1
def getRecordCount(self):
return len(self.data) / self.clmcnt
def get(self, rowidx, clmidx):
return self.data[rowidx * self.clmcnt + clmidx]
class CategoryStructure(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "__instance__"):
cls.__instance__ = super(CategoryStructure, cls).__new__(cls, *args, **kwargs)
cls._data = SheetData(u"Category structure", 3, 2, 2, 5)
return cls.__instance__
def getRecordCount(self):
return self._data.getRecordCount()
def get(self, rowidx, clmidx):
return self._data.get(rowidx, clmidx)
I wrote like this, but I don't like the functions getRecordCount () and get () implemented in SheetData implemented in CategoryStructure, so I tried to find out if inheritance (multiple inheritance) could be used.
I referred to the following site. -Advantages and disadvantages of Python super-- methane blog
The inheritance source init () must be explicitly called. In the case of multiple inheritance in the site written above, when specifying an argument (argument other than self) in init (), it is necessary to explicitly specify the inheritance source class, so implement it as such. (Just in case, if I implemented it without specifying the class name, it didn't work as I expected (SheetData init wasn't called))
The only change is the CategoryStructure class.
class CategoryStructure(object, SheetData):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "__instance__"):
cls.__instance__ = super(CategoryStructure, cls).__new__(cls, *args, **kwargs)
return cls.__instance__
def __init__(self, *args, **kwargs):
#Although self is an instance object, it is implemented as a singleton, so the following judgment is
#Works well
if not hasattr(self, "data"):
#super(CategoryStructure, self).__init__(self, u"Category structure", 3, 2, 2, 5)
#the above(comment)Then SheetData.__init__()Does not work
#Explicitly specify the class name__init__()Call
SheetData.__init__(self, u"Category structure", 3, 2, 2, 5)
I'm still groping, but for the time being, it was refreshing.
Recommended Posts